Search code examples
amazon-web-servicesaws-cdk

In AWS CDK, how to set ClientIpPreservation on NLB Global Accelerator endpoint?


I have a Global Accelerator that points to a Network Load Balancer (that has a security group). According to AWS documentation, by default the IP address preservation is turned off, But it's possible to turn it on.

I can't figure out how to turn on IP address preservation for NetworkLoadBalancerEndpoint through the CDK. NetworkLoadBalancerEndpoint's only properties appear to be NLB and weight.

That's the code I have written to create the accelerator and the endpoint:

class GlobalAcceleratorConstruct(Construct):

def __init__(self, scope: Construct, id_: str, nlb: NetworkLoadBalancer) -> None:
    super().__init__(scope, id_)

    accelerator = aws_globalaccelerator.Accelerator(self, f'NlbAccelerator')

    listener = aws_globalaccelerator.Listener(self, f'NlbAcceleratorListener', accelerator=accelerator,
               port_ranges=[aws_globalaccelerator.PortRange(from_port=NLB_LISTENING_PORT)])

    endpoint = NetworkLoadBalancerEndpoint(nlb)
    self._endpoint_group = aws_globalaccelerator.EndpointGroup(self, 'NlbAcceleratorEndpointGroup', listener=listener,
               endpoints=[endpoint])

Solution

  • Unfortunately NetworkLoadBalancerEndpoint doesn't support PreserveClientIP parameter. I hope it will be added somehow in the future.

    For temporary solution you can use CfnEndpointGroup with EndpointConfigurationProperty.

    endpoint_configurations = []
    endpoint_configurations.append(                      
        
    aws_globalaccelerator.CfnEndpointGroup.EndpointConfigurationProperty(
                            endpoint_id=load_balancer_arn,
                            weight=128,
                            client_ip_preservation_enabled=True
                        ))
    
    aws_globalaccelerator.CfnEndpointGroup(
                self, 'EndpointGroup',
                listener_arn=listener.listener_arn,
                endpoint_group_region=region,
                endpoint_configurations=endpoint_configurations,
            )