EC2 インスタンスの VPC 関連付けの確認

EC2 インスタンスとサブネットの実際の VPC 関連付けを確認し、ネットワークアクセスを明示的に管理してください。

説明

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 アドレスを要求します。

参考資料