説明
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 のままであり、プライベート配置への変更例ではありません。実際の外部接続は経路やセキュリティグループにも左右されます。