Skip to content

ec2: specifying EC2 private IP with associate public IP enabled generates invalid CFn #26187

@hoppersoft

Description

@hoppersoft

Describe the bug

When both associatePublicIpAddress and privateIpAddress properties are supplied to the EC2 Instance construct, an invalid CloudFormation template is generated due to the presence of both PrivateIpAddess and NetworkInterfaces properties on the AWS::EC2::Instance resource.

Expected Behavior

The value of the privateIpAddress property should be added to the generated NetworkInterface, omitting the resource-level PrivateIpAddress property.

Current Behavior

The generated template leaves the PrivateIpAddress property populated but also includes a NetworkInterfaces property, resulting in a deployment error: "Network interfaces and an instance-level private IP address may not be specified on the same request"

Reproduction Steps

  1. Create an EC2 instance (using Typescript syntax below):
new Instance(stack, 'Instance', {
      vpc,
      vpcSubnets: { subnetType: SubnetType.PUBLIC },
      securityGroup,
      machineImage: new AmazonLinuxImage(),
      instanceType: InstanceType.of(InstanceClass.T3, InstanceSize.LARGE),
      privateIpAddress: privateIpAddress,
      associatePublicIpAddress: true,
    });
  1. Run cdk synth, capturing the output.
  2. Attempt to cdk deploy - this will result in the "Network interfaces and an instance-level private IP address may not be specified on the same request" error and rollback.
  3. (Extra credit) Inspect the AWS::EC2::Instance resource; you should see something like the below:
  <Resource ID>:
    Type: AWS::EC2::Instance
    Properties:
      #
      # Omitting other properties for brevity
      NetworkInterfaces:
        - AssociatePublicIpAddress: true
          DeviceIndex: "0"
          GroupSet:
            - Fn::GetAtt:
                - <Security Group ID>
                - GroupId
          SubnetId:
            Ref: <Subnet ID>
      PrivateIpAddress: 10.0.1.10

Possible Solution

The logic used to detect the use of associatePublicIpAddress should also include moving the value of privateIpAddress to the NetworkInterface object.

Additional Information/Context

No response

CDK CLI Version

2.85.0 (build 4e0d726)

Framework Version

No response

Node.js Version

18.0.0

OS

Windows, Mac

Language

Typescript

Language Version

5.1.3

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    aws-cdk-libRelated to the aws-cdk-lib packagebugThis issue is a bug.effort/mediumMedium work item – several days of effortp1

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions