Geoffrey-ap
Geoffrey-ap

Reputation: 380

How to associate an elastic ip with a NAT instance in AWS CDK?

I created a NAT instance using AWS CDK.

const nat_instance_provider = ec2.NatProvider.instance({
    instanceType: new ec2.InstanceType('t3.micro')
});

Then I created an elastic IP.

const elastic_ip = new ec2.CfnEIP(this, "elastic_ip");

Now I need to associate the ec2 instance with the elastic IP.

let ec2Assoc = new ec2.CfnEIPAssociation(this, "Ec2Association", {
    eip: elastic_ip.ref,
    instanceId: <EC2 ID> ???
});

The issue I'm facing is that so far I couldn't find a way to get the instance ID and I feel this is a limitation but I might be missing something.

Upvotes: 1

Views: 1122

Answers (1)

fedonev
fedonev

Reputation: 25639

The NAT instance resources are children of the vpc's subnets, which are not directly exposed. You can get a reference to the underlying CloudFormation AWS::EC2::Instance resources using the CDK's escape hatch syntax.

const vpc = new ec2.Vpc(this, 'MyVpc', {
  natGatewayProvider: nat_instance_provider,
});

// Escape hatch - find the nested child IConstruct by its CDK-assigned id and cast it to ec2.Instance
// finding the ids sometimes requires detective work in the cdk source code or with console.log.
// if the id references are valid, it will have the instanceId
const natInstancePublicSubnet1 = vpc.node.findChild('PublicSubnet1').node.findChild('NatInstance') as ec2.Instance;

const ec2Assoc = new ec2.CfnEIPAssociation(this, 'Ec2Association', {
  eip: elastic_ip.ref,
  instanceId: natInstancePublicSubnet1.instanceId,
});

Disclaimer: Using escape hatches is perfectly OK and sometimes unavoidable. However, it's often (but not always) a sign you are going "off piste" with an advanced, non-standard solution. I personally have zero knowledge about the setup you are attempting.

Upvotes: 2

Related Questions