How to create Elastic IP association with an EC2 instance using AWS CDK?

Viewed 5204

In AWS CDK, I have an EC2 instance and Elastic IP created as follows:

    // EC2 Instance
    let ec2Instance = new ec2.Instance(this, "EC2Instance", {
        instanceType: ec2.InstanceType.of(InstanceClass.T2, InstanceSize.MICRO),
        vpc: vpc,
        securityGroup: securityGroupEc2,
        keyName: Config.keyPairName,
        machineImage: new ec2.GenericLinuxImage({"eu-west-1": Config.ec2ImageAmi}),
        blockDevices: [{deviceName: "/dev/sda1", volume: ec2.BlockDeviceVolume.ebs(30)}]
    });

    // Elastic IP
    let eip = new ec2.CfnEIP(this, "Ip");

I have difficulties to understand how I can declare an association between these, as I can not perceive using AWS CDK documentation how to declare that. Seems that I need AWS::EC2::EIPAssociation.EIP: string to supply and I am missing as to how to get it from the eip object.

2 Answers

It wasn't explained very well, but the solution is:

    // EC2 Instance <> EIP
    let ec2Assoc = new ec2.CfnEIPAssociation(this, "Ec2Association", {
        eip: eip.ref,
        instanceId: ec2Instance.instanceId
    });

For Cfn* CDK resources, I find that the CloudFormation docs are much more informative than the CDK API.

The CloudFormation docs for AWS::EC2::EIP show that there is an instanceId property that can be used when creating the EIP, which I believe should avoid the need to create a CfnEIPAssociation separately.

Related