Review EC2 instance VPC association

Verify the actual VPC associations of the EC2 instance and subnet, and manage network access explicitly.

Description

EC2 launches instances in VPC subnets. If the instance omits its subnet, EC2 may use a default subnet or fail to launch.

Potential impact

CloudFormation requires VpcId when creating a subnet. The missing value in the Before example prevents deployment.

Remediation

Set the subnet’s VpcId to the intended VPC. Point the instance’s SubnetId to that subnet and restrict its routes and security group rules to required connections.

Examples

Supply ImageId and KeyName for your environment. The excerpts omit route tables and security groups.

Before

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 ]    # Select the first Availability Zone in the list
      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

After

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 ]    # Select the first Availability Zone in the list
      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

The instance still requests a public IPv4 address because AssociatePublicIpAddress remains true.

References