question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Elastic IP association for generated NAT in VPC

See original GitHub issue

🚀 Feature Request

General Information

  • 👋 I may be able to implement this feature request
  • ⚠️ This feature might incur a breaking change

Description

It would be great to be able to create a NAT gateway and associate an EIP with it. Currently I create a VPC and that automatically generates a NAT for me. But it’s not possible to alter the NAT or to associate an EIP with the generated NAT.

My use case is that I need a Fargate outbound request mapped to a static IP. This IP will be whitelisted in our on-premise datacenter.

Proposed Solution

new Vpc(this, "myVpc", {
    maxAzs: 2,
    cidr: '10.0.0.0/16',
    natGateways: 1,
    allocationIDs: ['eipalloc-12abcde34a5fab67']           
    subnetConfiguration: [
        {
            cidrMask: 24,
            name: 'sonar_nat_lb',
            subnetType: SubnetType.PUBLIC
         },
         {
            cidrMask: 24,
            name: 'sonar_fargate',
            subnetType: SubnetType.PRIVATE
          }
    ]
});

Allocation ID can be optional as the NAT Gateway will default create its own EIP.

Environment

  • CDK CLI Version: 1.8.0
  • Module Version: 1.8.0
  • OS: all
  • Language: TypeScript

Other information

On a sidenote, it is also not possible to create an EIP with CDK, but that’s a different feature-request.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:5
  • Comments:12 (2 by maintainers)

github_iconTop GitHub Comments

6reactions
christophegrallcommented, Nov 9, 2020

@xian13 @rix0rrr @logemann

A raw example using a NatProvider. Here only one EIP was created using the console. It needs some improvements in order to manage more EIPs and options.

import { NatProvider, CfnNatGateway } from '@aws-cdk/aws-ec2';



export interface MyNatGatewayProps {
   allocationIds: string[];
}

export class MyNatGatewayProvider extends ec2.NatProvider {

  private gateways: PrefSet<string> = new PrefSet<string>();

  private allocationIds: string[] = [];

  constructor(private props: MyNatGatewayProps) {
    super();
    this.allocationIds = props.allocationIds;
  }

  public configureNat(options: ec2.ConfigureNatOptions) {
    // Create the NAT gateways
    for (const sub of options.natSubnets) {
 
       if(this.allocationIds.length > 0){
          sub.addNatGateway = () => {

            const test = this.allocationIds[0]
            
            const ngw = new CfnNatGateway(sub, `NATGateway`, {
              subnetId: sub.subnetId,
              allocationId: this.allocationIds[0]
            });
            this.allocationIds.shift();
            return ngw;
          };
      } 

      const gateway = sub.addNatGateway();
      this.gateways.add(sub.availabilityZone, gateway.ref);
    }
    // Add routes to them in the private subnets
    for (const sub of options.privateSubnets) {
      this.configureSubnet(sub);
    }
  }

  public configureSubnet(subnet: ec2.PrivateSubnet) {
    const az = subnet.availabilityZone;
    const gatewayId = this.gateways.pick(az);
    subnet.addRoute('DefaultRoute', {
      routerType: ec2.RouterType.NAT_GATEWAY,
      routerId: gatewayId,
      enablesInternetConnectivity: true,
    });
  }

  public get configuredGateways(): ec2.GatewayConfig[] {
    return this.gateways.values().map((x: any[]) => ({ az: x[0], gatewayId: x[1] }));
  }

}

class PrefSet<A> {
  private readonly map: Record<string, A> = {};
  private readonly vals = new Array<[string, A]>();
  private next: number = 0;

  public add(pref: string, value: A) {
    this.map[pref] = value;
    this.vals.push([pref, value]);
  }

  public pick(pref: string): A {
    if (this.vals.length === 0) {
      throw new Error('Cannot pick, set is empty');
    }

    if (pref in this.map) { return this.map[pref]; }
    return this.vals[this.next++ % this.vals.length][1];
  }

  public values(): Array<[string, A]> {
    return this.vals;
  }
}



export class CdkStack extends cdk.Stack {

  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const vpc = new ec2.Vpc(this, 'VPC', 
      {
        natGatewayProvider: new MyNatGatewayProvider({
          allocationIds: ["eipalloc-03db274e099d85676"]
        }),
        cidr: "10.200.0.0/16",
        subnetConfiguration: [
          {
            cidrMask: 24,
            name: 'PUBLIC',
            subnetType: ec2.SubnetType.PUBLIC,
          },
          {
            cidrMask: 24,
            name: 'PRIVATE',
            subnetType: ec2.SubnetType.PRIVATE,
          }
        ]
      }
    );
4reactions
zrieqcommented, Nov 9, 2021

After contacting AWS Support for CDK issues, I got this working by using this code after the VPC creation:

         // Remove allocation of unwanted EIPs.
        vpc.getPublicSubnets().forEach(subnet -> {
            subnet.getNode().tryRemoveChild("EIP");
        });
Read more comments on GitHub >

github_iconTop Results From Across the Web

Associate Elastic IP addresses with resources in your VPC
Use Elastic IP addresses to remap public IPv4 addresses between instances in your VPC. ... see Connect to the internet or other networks...
Read more >
Allocate Elastic IPs for NAT Gateways - Trend Micro
Ensure that an Elastic IP (EIP) is allocated for each NAT gateway that you want to deploy within your AWS account.
Read more >
Why does a AWS NAT Gateway require an ElasticIP?
As the image in the question indicates, the Elastic IP (EIP) is an association. It is the IGW that is translating the NATG's...
Read more >
NAT Gateway Archives - Jayendra's Cloud Certification Blog
cannot associate an elastic IP address with a private NAT gateway. internet gateway can be attached to a VPC with a private NAT...
Read more >
AWS VPC Tutorial Part III Elastic IP and NAT - Studytrails
We will build a NAT gateway, however, the gateway needs an IP address. AWS provides Elastic IP addresses, that you can create on...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found