Search code examples
amazon-web-servicesaws-cdk

Assign a Static Elastic IP to Application Load Balancer


How to create a Network Load Balancer with one or more Elastic IP addresses in front of the Application Load Balancer using AWS CDK?

This should allow having fixed IP addresses for the load balancer. The article I need a static IP address for my Application Load Balancer. How can I register an Application Load Balancer behind a Network Load Balancer? recommends this approach.

The CDK API manual does not cover this use case. The class NetworkLoadBalancer (construct) lacks a definition of the SubnetMappings property. This looks like an issue in the documentation or the library.

The code should be preferable in TypeScript.


Solution

  • Instead of assigning a static IP directly to your ALB, you can link a AWS Global Accelerator to your ALB and it in turn will give you two static ip addresses. It's like adding a layer 4 load balancer in front of your load balancer.

    I did this and then added a CNAME with DNS validation that links to the Global Accelerator. I then added the certificate to the load balancer.

    According to Amazon Q, as long as the Global Accelerator is not deleted the two static ip addresses are retained.

    From this article: The global static IP addresses provisioned by Global Accelerator remain assigned to you for as long as your accelerator exists, even if you disable the accelerator and it no longer accepts or routes traffic

    Some code directly from the docs.

    declare const alb: elbv2.ApplicationLoadBalancer;
    declare const listener: globalaccelerator.Listener;
    
    listener.addEndpointGroup('Group', {
      endpoints: [
        new ga_endpoints.ApplicationLoadBalancerEndpoint(alb, {
          weight: 128,
          preserveClientIp: true,
        }),
      ],
    });
    

    As a side effect and actually the main purpose, this can help improve the availability, performance, and fault tolerance of your application by directing traffic to the closest and healthiest backend ALB instance.

    preserveClientIp added a X-Forwarded-For header and has nothing to do with retaining the static ip addresses.