설명
EC2 인스턴스는 VPC의 서브넷에 배치됩니다. 인스턴스에서 서브넷을 생략하면 환경에 따라 기본 서브넷이 선택되거나 생성이 실패할 수 있으며, VPC 밖에 인스턴스가 생성되는 것은 아닙니다.
CloudFormation의 AWS::EC2::Subnet에는 VpcId가 필요합니다. 이 값이 빠진 서브넷은 배포 오류이며, VPC 연결을 지정해도 공개 주소나 외부 접근이 자동으로 차단되지는 않습니다.
잠재적 영향
필수 VPC 참조가 없으면 배포가 실패할 수 있습니다. 의도와 다른 서브넷이나 보안 그룹을 사용하면 불필요한 연결이 허용되거나 필요한 통신이 중단될 수 있습니다.
해결 방법
서브넷의 VpcId와 인스턴스의 서브넷 참조를 올바르게 연결하세요. 실제 라우팅, 공개 주소 할당과 보안 그룹을 검토하고 필요한 클라이언트만 접근하도록 제한하세요.
예시
환경에 맞는 ImageId와 KeyName 입력을 별도로 제공하는 발췌입니다. 경로 테이블과 보안 그룹 설정은 생략되어 있습니다.
변경 전
yaml
Resources:
VPC:
Type: AWS::EC2::VPC
Properties:
CidrBlock: 10.1.0.0/16
EnableDnsSupport: true
EnableDnsHostnames: true
Tags:
- Key: Name
Value: !Join ['', [!Ref "AWS::StackName", "-VPC" ]]
InternetGateway:
Type: AWS::EC2::InternetGateway
DependsOn: VPC
AttachGateway:
Type: AWS::EC2::VPCGatewayAttachment
Properties:
VpcId: !Ref VPC
InternetGatewayId: !Ref InternetGateway
PublicSubnetA:
Type: AWS::EC2::Subnet
Properties:
CidrBlock: 10.1.10.0/24
AvailabilityZone: !Select [ 0, !GetAZs ] # 목록의 첫 번째 가용 영역 선택
Tags:
- Key: Name
Value: !Sub ${AWS::StackName}-Public-A
Ec2Instance:
Type: AWS::EC2::Instance
Properties:
ImageId: !Ref ImageId
KeyName: !Ref KeyName
NetworkInterfaces:
- AssociatePublicIpAddress: "true"
DeviceIndex: 0
SubnetId: !Ref PublicSubnetA
PublicSubnetA의 필수 VpcId가 없어 이 서브넷을 생성할 수 없습니다.
변경 후
yaml
Resources:
VPC:
Type: AWS::EC2::VPC
Properties:
CidrBlock: 10.1.0.0/16
EnableDnsSupport: true
EnableDnsHostnames: true
Tags:
- Key: Name
Value: !Join ['', [!Ref "AWS::StackName", "-VPC" ]]
InternetGateway:
Type: AWS::EC2::InternetGateway
DependsOn: VPC
AttachGateway:
Type: AWS::EC2::VPCGatewayAttachment
Properties:
VpcId: !Ref VPC
InternetGatewayId: !Ref InternetGateway
PublicSubnetA:
Type: AWS::EC2::Subnet
Properties:
VpcId: !Ref VPC
CidrBlock: 10.1.10.0/24
AvailabilityZone: !Select [ 0, !GetAZs ] # 목록의 첫 번째 가용 영역 선택
Tags:
- Key: Name
Value: !Sub ${AWS::StackName}-Public-A
Ec2Instance:
Type: AWS::EC2::Instance
Properties:
ImageId: !Ref ImageId
KeyName: !Ref KeyName
NetworkInterfaces:
- AssociatePublicIpAddress: "true"
DeviceIndex: 0
SubnetId: !Ref PublicSubnetA
서브넷을 VPC에 연결합니다. AssociatePublicIpAddress는 여전히 true이므로 프라이빗 배치로 바뀌는 예시는 아닙니다. 실제 외부 연결은 경로와 보안 그룹에도 달려 있습니다.