I am deploying a CDK Stack that includes a VPC with static Elastic IPs in AWS.
I want to ensure that the IPs remain the same even if I redeploy the whole Stack containing the VPC, as I need to avoid having users update their API keys with the new whitelist IPs (re-generated on deploy).
I am currently "creating" the Elastic IPs using the CDK code below:
const natGatewayProvider = NatInstanceProvider.instance({
instanceType: new InstanceType('t3.micro')
});
const vpcFargate = new Vpc(stack, 'WhiteVpcFargate', {
vpcName: 'white-vpc-fargate',
natGateways: 1, // Automatically creates an Elastic IP
natGatewayProvider: natGatewayProvider,
maxAzs: 2
});
// I'm creating more EIPs and associating to that NAT
const allEIPs = natGatewayProvider.configuredGateways.map((nat, index) =>{
for(let i=0;i<3;i++){
new CfnEIP(stack, `NatInstanceEIP${index + 1}_${i}`, {
instanceId: nat.gatewayId,
tags: [
{ key: 'Name', value: `NatInstanceEIP${index + 1}_${i}` },
],
})
}
}
)
What is the best practice to ensure that the Elastic IPs remain the same even after redeploying the whole Stack containing the VPC?
I think I should create the EIPs in a different CDK Stack, create them manually with the CLI, or create them on the Cloud Console, and then somehow reference those EIPs on the NAT Gateway definition in AWS CDK doing the Associations using CfnEIPAssociation, but I'm not really sure if that's the right path to follow.
Probably not the best solution but I end up creating the EIPs and then associating them with the NAT.
The first part of EIPs creation has to be done outside CDK, so I'm using an aws-sdk one-time NodeJs script.
EIPs One Time Creation:
I run this method and used the AllocationIds printed in the output to setup the NAT Gateway using AWS CDK. (If you lost the logs of the execution of the createElasticIPs method, you can still see the AllocationId of each EIP using AWS Console).
CDK NAT Gateway Definition:
Probably instead of setting them hard-coded I should pull the ids using CDK...
Here the implementation of the CustomNatProvider: