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.
2
Answers
Before answering the question about the static IP address for the load balancer, I want to suggest an alternative solution.
Alternative solution – register ALB with Route53
We can create a DNS record for the ALB in Route53 using CDK. The code is straightforward. Unfortunately, this solution does not work nicely if the DNS zone is not hosted by the AWS Route53.
Issues with fixed address for the Network Load Balancer
At the moment of writing, CDK constructs do not have the option to assign a static IP address to the Network Load Balancer. There are several open issues on GitHub: SubnetMappings support for LoadBalancer #7424, Add support for SubnetMapping to Network Load Balancer #9696.
In a nutshell, using the
SubnetMappings
allows the load balancer to specify one or more Elastic IP addresses, but theNetworkLoadBalancer
class does not have theSubnetMappings
property.Issue 7424 is more than two years old. Instead of waiting, we might want to go for a workaround if we must.
Workaround to assign Elastic IP address to the NLB
We will register an Elastic IP address, create a Network Load Balancer and assign it the IP address. I also add code to import VPC and create a simple Application Load Balancer for completeness. Please, check the code below and comments on the code. Note that the network load balancer and the Elastic IP start responding with some delay after the stack creation.
The screenshot below shows the IP address association in the Console. You can add more associations to the
cfnNlb.subnetMappings
list. If you want to remove some, you must recreate the load balancer.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.
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.