설명
EC2는 VPC 서브넷에서 인스턴스를 시작합니다. 인스턴스에 서브넷을 지정하지 않으면 기본 서브넷을 사용하거나 시작에 실패할 수 있습니다.
잠재적 영향
CloudFormation에서 서브넷 자체를 만들 때는 VpcId가 필수입니다. 변경 전 예시는 이 값이 없어 배포에 실패합니다.
해결 방법
서브넷의 VpcId에 대상 VPC를 지정하고 인스턴스의 SubnetId가 그 서브넷을 참조하도록 하세요. 경로와 보안 그룹은 필요한 연결만 허용하세요.
예시
환경에 맞는 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
변경 후
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
변경 후에도 AssociatePublicIpAddress는 true이므로 인스턴스가 퍼블릭 IPv4 주소를 요청합니다.