1

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.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Geoffrey-ap
  • 380
  • 3
  • 12

1 Answers1

2

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.

fedonev
  • 20,327
  • 2
  • 25
  • 34
  • Hey @fedonev , Thanks for the answer, this answer is great, I need to use a NAT Instance instead of a NAT Gateway to save money since the NAT Gateway is too expensive, I also need to have a static IP in the instance so that it can be whitelisted by other resources I have to consume. I don't really think there's a better/standard/cost efficient way to accomplish this. Appreciate if you have additional comments. – Geoffrey-ap Feb 20 '22 at 15:52