Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

associate custom Elastic IP to NAT Gateway with AWS CDK

After struggling with that for several hours, here is my question. I am using CDK to create a VPC in the most simple form currently:

let vpc = new Vpc(this, "myVpc", {maxAzs: 1});

This gets me a public Subnet and a private one with the all the Gateways (internet and NAT). My NAT Gateway got a public EIP from the AWS pool. Of course when i destroy the stack and re-create it, i will get a new EIP from AWS, but THIS i dont want.

What i want is: Creating an Elastic IP outside of my CDK project (manually via CLI or AWS Console) and attach it to my NAT GW, so that even after destroying the stack, i can re-attach my (external) EIP to the "new" NAT GW.

So there must be a way to not have the AWS::EC2::NatGateway created automatically by the VPC but manually with the proper EIP association and then attach it to the VPC / Public Subnet. Pretty much the same way i can explicitly define Subnets and associate them with the VPC instead of CDK construct magic.

like image 620
Logemann Avatar asked Sep 17 '25 12:09

Logemann


2 Answers

You can refer here https://github.com/aws/aws-cdk/issues/4067 at the last post.

You can define EIP allocations then assign it into Nat Gateway while CDK deployment.

Of course, you must manually create EIP first.

like image 151
Thanh Nguyen Van Avatar answered Sep 20 '25 07:09

Thanh Nguyen Van


For Java CDK you can use natGatewayProvider(NatProvider.gateway(NatGatewayProps.builder().eipAllocationIds(Collections.singletonList("eipalloc-id")).build()))

The full example to create VPC with manually configured EIP for NAT:

Vpc.Builder.create(this, "vpc")
        .natGateways(1)
        .natGatewayProvider(NatProvider.gateway(NatGatewayProps.builder().eipAllocationIds(Collections.singletonList("eipalloc-id")).build()))
        .maxAzs(3)
        .subnetConfiguration(
            Arrays.asList(
                SubnetConfiguration.builder()
                    .subnetType(SubnetType.PRIVATE)
                    .cidrMask(24)
                    .name("mc")
                    .build(),
                SubnetConfiguration.builder()
                    .subnetType(SubnetType.PUBLIC)
                    .cidrMask(24)
                    .name("Ingress")
                    .build(),
                SubnetConfiguration.builder()
                    .subnetType(SubnetType.ISOLATED)
                    .cidrMask(24)
                    .name("app")
                    .build()
            )
        )
        .cidr("10.0.0.0/16").build();

For other languages look into https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-ec2.Vpc.html#natgatewayprovider

like image 29
Ivan Metla Avatar answered Sep 20 '25 07:09

Ivan Metla