Skip to content
v2.273.0

Amazon Elastic Load Balancing V2 Construct Library ​

The aws-cdk-lib/aws-elasticloadbalancingv2 package provides constructs for configuring application and network load balancers.

For more information, see the AWS documentation for Application Load Balancers and Network Load Balancers.

Defining an Application Load Balancer ​

You define an application load balancer by creating an instance of ApplicationLoadBalancer, adding a Listener to the load balancer and adding Targets to the Listener:

ts
import { AutoScalingGroup } from 'aws-cdk-lib/aws-autoscaling';
declare const asg: AutoScalingGroup;
declare const vpc: ec2.Vpc;

// Create the load balancer in a VPC. 'internetFacing' is 'false'
// by default, which creates an internal load balancer.
const lb = new elbv2.ApplicationLoadBalancer(this, 'LB', {
  vpc,
  internetFacing: true
});

// Add a listener and open up the load balancer's security group
// to the world.
const listener = lb.addListener('Listener', {
  port: 80,

  // 'open: true' is the default, you can leave it out if you want. Set it
  // to 'false' and use `listener.connections` if you want to be selective
  // about who can access the load balancer.
  open: true,
});

// Create an AutoScaling group and add it as a load balancing
// target to the listener.
listener.addTargets('ApplicationFleet', {
  port: 8080,
  targets: [asg]
});
python
from aws_cdk.aws_autoscaling import AutoScalingGroup
# asg: AutoScalingGroup
# vpc: ec2.Vpc


# Create the load balancer in a VPC. 'internetFacing' is 'false'
# by default, which creates an internal load balancer.
lb = elbv2.ApplicationLoadBalancer(self, "LB",
    vpc=vpc,
    internet_facing=True
)

# Add a listener and open up the load balancer's security group
# to the world.
listener = lb.add_listener("Listener",
    port=80,

    # 'open: true' is the default, you can leave it out if you want. Set it
    # to 'false' and use `listener.connections` if you want to be selective
    # about who can access the load balancer.
    open=True
)

# Create an AutoScaling group and add it as a load balancing
# target to the listener.
listener.add_targets("ApplicationFleet",
    port=8080,
    targets=[asg]
)
java
import software.amazon.awscdk.services.autoscaling.AutoScalingGroup;
AutoScalingGroup asg;
Vpc vpc;


// Create the load balancer in a VPC. 'internetFacing' is 'false'
// by default, which creates an internal load balancer.
ApplicationLoadBalancer lb = ApplicationLoadBalancer.Builder.create(this, "LB")
        .vpc(vpc)
        .internetFacing(true)
        .build();

// Add a listener and open up the load balancer's security group
// to the world.
ApplicationListener listener = lb.addListener("Listener", BaseApplicationListenerProps.builder()
        .port(80)

        // 'open: true' is the default, you can leave it out if you want. Set it
        // to 'false' and use `listener.connections` if you want to be selective
        // about who can access the load balancer.
        .open(true)
        .build());

// Create an AutoScaling group and add it as a load balancing
// target to the listener.
listener.addTargets("ApplicationFleet", AddApplicationTargetsProps.builder()
        .port(8080)
        .targets(List.of(asg))
        .build());
csharp
using Amazon.CDK.AWS.AutoScaling;
AutoScalingGroup asg;
Vpc vpc;


// Create the load balancer in a VPC. 'internetFacing' is 'false'
// by default, which creates an internal load balancer.
var lb = new ApplicationLoadBalancer(this, "LB", new ApplicationLoadBalancerProps {
    Vpc = vpc,
    InternetFacing = true
});

// Add a listener and open up the load balancer's security group
// to the world.
var listener = lb.AddListener("Listener", new BaseApplicationListenerProps {
    Port = 80,

    // 'open: true' is the default, you can leave it out if you want. Set it
    // to 'false' and use `listener.connections` if you want to be selective
    // about who can access the load balancer.
    Open = true
});

// Create an AutoScaling group and add it as a load balancing
// target to the listener.
listener.AddTargets("ApplicationFleet", new AddApplicationTargetsProps {
    Port = 8080,
    Targets = new [] { asg }
});
go
import "github.com/aws/aws-cdk-go/awscdk"
var asg AutoScalingGroup
var vpc Vpc


// Create the load balancer in a VPC. 'internetFacing' is 'false'
// by default, which creates an internal load balancer.
lb := elbv2.NewApplicationLoadBalancer(this, jsii.String("LB"), &ApplicationLoadBalancerProps{
	Vpc: Vpc,
	InternetFacing: jsii.Boolean(true),
})

// Add a listener and open up the load balancer's security group
// to the world.
listener := lb.AddListener(jsii.String("Listener"), &BaseApplicationListenerProps{
	Port: jsii.Number(80),

	// 'open: true' is the default, you can leave it out if you want. Set it
	// to 'false' and use `listener.connections` if you want to be selective
	// about who can access the load balancer.
	Open: jsii.Boolean(true),
})

// Create an AutoScaling group and add it as a load balancing
// target to the listener.
listener.AddTargets(jsii.String("ApplicationFleet"), &AddApplicationTargetsProps{
	Port: jsii.Number(8080),
	Targets: []IApplicationLoadBalancerTarget{
		asg,
	},
})

The security groups of the load balancer and the target are automatically updated to allow the network traffic.

NOTE: If the @aws-cdk/aws-elasticloadbalancingV2:albDualstackWithoutPublicIpv4SecurityGroupRulesDefault feature flag is set (the default for new projects), and addListener() is called with open: true, the load balancer's security group will automatically include both IPv4 and IPv6 ingress rules when using IpAddressType.DUAL_STACK_WITHOUT_PUBLIC_IPV4.

For existing projects that only have IPv4 rules, you can opt-in to IPv6 ingress rules by enabling the feature flag in your cdk.json file. Note that enabling this feature flag will modify existing security group rules.

One (or more) security groups can be associated with the load balancer; if a security group isn't provided, one will be automatically created.

ts
declare const vpc: ec2.Vpc;

const securityGroup1 = new ec2.SecurityGroup(this, 'SecurityGroup1', { vpc });
const lb = new elbv2.ApplicationLoadBalancer(this, 'LB', {
  vpc,
  internetFacing: true,
  securityGroup: securityGroup1, // Optional - will be automatically created otherwise
});

const securityGroup2 = new ec2.SecurityGroup(this, 'SecurityGroup2', { vpc });
lb.addSecurityGroup(securityGroup2);
python
# vpc: ec2.Vpc


security_group1 = ec2.SecurityGroup(self, "SecurityGroup1", vpc=vpc)
lb = elbv2.ApplicationLoadBalancer(self, "LB",
    vpc=vpc,
    internet_facing=True,
    security_group=security_group1
)

security_group2 = ec2.SecurityGroup(self, "SecurityGroup2", vpc=vpc)
lb.add_security_group(security_group2)
java
Vpc vpc;


SecurityGroup securityGroup1 = SecurityGroup.Builder.create(this, "SecurityGroup1").vpc(vpc).build();
ApplicationLoadBalancer lb = ApplicationLoadBalancer.Builder.create(this, "LB")
        .vpc(vpc)
        .internetFacing(true)
        .securityGroup(securityGroup1)
        .build();

SecurityGroup securityGroup2 = SecurityGroup.Builder.create(this, "SecurityGroup2").vpc(vpc).build();
lb.addSecurityGroup(securityGroup2);
csharp
Vpc vpc;


var securityGroup1 = new SecurityGroup(this, "SecurityGroup1", new SecurityGroupProps { Vpc = vpc });
var lb = new ApplicationLoadBalancer(this, "LB", new ApplicationLoadBalancerProps {
    Vpc = vpc,
    InternetFacing = true,
    SecurityGroup = securityGroup1
});

var securityGroup2 = new SecurityGroup(this, "SecurityGroup2", new SecurityGroupProps { Vpc = vpc });
lb.AddSecurityGroup(securityGroup2);
go
var vpc Vpc


securityGroup1 := ec2.NewSecurityGroup(this, jsii.String("SecurityGroup1"), &SecurityGroupProps{
	Vpc: Vpc,
})
lb := elbv2.NewApplicationLoadBalancer(this, jsii.String("LB"), &ApplicationLoadBalancerProps{
	Vpc: Vpc,
	InternetFacing: jsii.Boolean(true),
	SecurityGroup: securityGroup1,
})

securityGroup2 := ec2.NewSecurityGroup(this, jsii.String("SecurityGroup2"), &SecurityGroupProps{
	Vpc: Vpc,
})
lb.AddSecurityGroup(securityGroup2)

Conditions ​

It's possible to route traffic to targets based on conditions in the incoming HTTP request. For example, the following will route requests to the indicated AutoScalingGroup only if the requested host in the request is either for example.com/ok or example.com/path:

ts
declare const listener: elbv2.ApplicationListener;
declare const asg: autoscaling.AutoScalingGroup;

listener.addTargets('Example.Com Fleet', {
  priority: 10,
  conditions: [
    elbv2.ListenerCondition.hostHeaders(['example.com']),
    elbv2.ListenerCondition.pathPatterns(['/ok', '/path']),
  ],
  port: 8080,
  targets: [asg]
});
python
# listener: elbv2.ApplicationListener
# asg: autoscaling.AutoScalingGroup


listener.add_targets("Example.Com Fleet",
    priority=10,
    conditions=[
        elbv2.ListenerCondition.host_headers(["example.com"]),
        elbv2.ListenerCondition.path_patterns(["/ok", "/path"])
    ],
    port=8080,
    targets=[asg]
)
java
ApplicationListener listener;
AutoScalingGroup asg;


listener.addTargets("Example.Com Fleet", AddApplicationTargetsProps.builder()
        .priority(10)
        .conditions(List.of(ListenerCondition.hostHeaders(List.of("example.com")), ListenerCondition.pathPatterns(List.of("/ok", "/path"))))
        .port(8080)
        .targets(List.of(asg))
        .build());
csharp
ApplicationListener listener;
AutoScalingGroup asg;


listener.AddTargets("Example.Com Fleet", new AddApplicationTargetsProps {
    Priority = 10,
    Conditions = new [] { ListenerCondition.HostHeaders(new [] { "example.com" }), ListenerCondition.PathPatterns(new [] { "/ok", "/path" }) },
    Port = 8080,
    Targets = new [] { asg }
});
go
var listener ApplicationListener
var asg AutoScalingGroup


listener.AddTargets(jsii.String("Example.Com Fleet"), &AddApplicationTargetsProps{
	Priority: jsii.Number(10),
	Conditions: []ListenerCondition{
		elbv2.ListenerCondition_HostHeaders([]*string{
			jsii.String("example.com"),
		}),
		elbv2.ListenerCondition_PathPatterns([]*string{
			jsii.String("/ok"),
			jsii.String("/path"),
		}),
	},
	Port: jsii.Number(8080),
	Targets: []IApplicationLoadBalancerTarget{
		asg,
	},
})

A target with a condition contains either pathPatterns or hostHeader, or both. If both are specified, both conditions must be met for the requests to be routed to the given target. priority is a required field when you add targets with conditions. The lowest number wins.

Every listener must have at least one target without conditions, which is where all requests that didn't match any of the conditions will be sent.

Convenience methods and more complex Actions ​

Routing traffic from a Load Balancer to a Target involves the following steps:

  • Create a Target Group, register the Target into the Target Group
  • Add an Action to the Listener which forwards traffic to the Target Group.

A new listener can be added to the Load Balancer by calling addListener(). Listeners that have been added to the load balancer can be listed using the listeners property. Note that the listeners property will throw an Error for imported or looked up Load Balancers.

Various methods on the Listener take care of this work for you to a greater or lesser extent:

  • addTargets() performs both steps: automatically creates a Target Group and the required Action.
  • addTargetGroups() gives you more control: you create the Target Group (or Target Groups) yourself and the method creates Action that routes traffic to the Target Groups.
  • addAction() gives you full control: you supply the Action and wire it up to the Target Groups yourself (or access one of the other ELB routing features).

Using addAction() gives you access to some of the features of an Elastic Load Balancer that the other two convenience methods don't:

  • Routing stickiness: use ListenerAction.forward() and supply a stickinessDuration to make sure requests are routed to the same target group for a given duration.
  • Weighted Target Groups: use ListenerAction.weightedForward() to give different weights to different target groups.
  • Fixed Responses: use ListenerAction.fixedResponse() to serve a static response (ALB only).
  • Redirects: use ListenerAction.redirect() to serve an HTTP redirect response (ALB only).
  • Authentication: use ListenerAction.authenticateOidc() to perform OpenID authentication before serving a request, or ListenerAction.authenticateJwt() to verify JSON Web Tokens (JWT) for secure service-to-service communications (see the aws-cdk-lib/aws-elasticloadbalancingv2-actions package for direct authentication integration with Cognito) (ALB only).

Here's an example of serving a fixed response at the /ok URL:

ts
declare const listener: elbv2.ApplicationListener;

listener.addAction('Fixed', {
  priority: 10,
  conditions: [
    elbv2.ListenerCondition.pathPatterns(['/ok']),
  ],
  action: elbv2.ListenerAction.fixedResponse(200, {
    contentType: 'text/plain',
    messageBody: 'OK',
  })
});
python
# listener: elbv2.ApplicationListener


listener.add_action("Fixed",
    priority=10,
    conditions=[
        elbv2.ListenerCondition.path_patterns(["/ok"])
    ],
    action=elbv2.ListenerAction.fixed_response(200,
        content_type="text/plain",
        message_body="OK"
    )
)
java
ApplicationListener listener;


listener.addAction("Fixed", AddApplicationActionProps.builder()
        .priority(10)
        .conditions(List.of(ListenerCondition.pathPatterns(List.of("/ok"))))
        .action(ListenerAction.fixedResponse(200, FixedResponseOptions.builder()
                .contentType("text/plain")
                .messageBody("OK")
                .build()))
        .build());
csharp
ApplicationListener listener;


listener.AddAction("Fixed", new AddApplicationActionProps {
    Priority = 10,
    Conditions = new [] { ListenerCondition.PathPatterns(new [] { "/ok" }) },
    Action = ListenerAction.FixedResponse(200, new FixedResponseOptions {
        ContentType = "text/plain",
        MessageBody = "OK"
    })
});
go
var listener ApplicationListener


listener.AddAction(jsii.String("Fixed"), &AddApplicationActionProps{
	Priority: jsii.Number(10),
	Conditions: []ListenerCondition{
		elbv2.ListenerCondition_PathPatterns([]*string{
			jsii.String("/ok"),
		}),
	},
	Action: elbv2.ListenerAction_FixedResponse(jsii.Number(200), &FixedResponseOptions{
		ContentType: jsii.String("text/plain"),
		MessageBody: jsii.String("OK"),
	}),
})

Here's an example of using OIDC authentication before forwarding to a TargetGroup:

ts
declare const listener: elbv2.ApplicationListener;
declare const myTargetGroup: elbv2.ApplicationTargetGroup;

listener.addAction('DefaultAction', {
  action: elbv2.ListenerAction.authenticateOidc({
    authorizationEndpoint: 'https://example.com/openid',
    // Other OIDC properties here
    clientId: '...',
    clientSecret: SecretValue.secretsManager('...'),
    issuer: '...',
    tokenEndpoint: '...',
    userInfoEndpoint: '...',

    // Next
    next: elbv2.ListenerAction.forward([myTargetGroup]),
  }),
});
python
# listener: elbv2.ApplicationListener
# my_target_group: elbv2.ApplicationTargetGroup


listener.add_action("DefaultAction",
    action=elbv2.ListenerAction.authenticate_oidc(
        authorization_endpoint="https://example.com/openid",
        # Other OIDC properties here
        client_id="...",
        client_secret=SecretValue.secrets_manager("..."),
        issuer="...",
        token_endpoint="...",
        user_info_endpoint="...",

        # Next
        next=elbv2.ListenerAction.forward([my_target_group])
    )
)
java
ApplicationListener listener;
ApplicationTargetGroup myTargetGroup;


listener.addAction("DefaultAction", AddApplicationActionProps.builder()
        .action(ListenerAction.authenticateOidc(AuthenticateOidcOptions.builder()
                .authorizationEndpoint("https://example.com/openid")
                // Other OIDC properties here
                .clientId("...")
                .clientSecret(SecretValue.secretsManager("..."))
                .issuer("...")
                .tokenEndpoint("...")
                .userInfoEndpoint("...")

                // Next
                .next(ListenerAction.forward(List.of(myTargetGroup)))
                .build()))
        .build());
csharp
ApplicationListener listener;
ApplicationTargetGroup myTargetGroup;


listener.AddAction("DefaultAction", new AddApplicationActionProps {
    Action = ListenerAction.AuthenticateOidc(new AuthenticateOidcOptions {
        AuthorizationEndpoint = "https://example.com/openid",
        // Other OIDC properties here
        ClientId = "...",
        ClientSecret = SecretValue.SecretsManager("..."),
        Issuer = "...",
        TokenEndpoint = "...",
        UserInfoEndpoint = "...",

        // Next
        Next = ListenerAction.Forward(new [] { myTargetGroup })
    })
});
go
var listener ApplicationListener
var myTargetGroup ApplicationTargetGroup


listener.AddAction(jsii.String("DefaultAction"), &AddApplicationActionProps{
	Action: elbv2.ListenerAction_AuthenticateOidc(&AuthenticateOidcOptions{
		AuthorizationEndpoint: jsii.String("https://example.com/openid"),
		// Other OIDC properties here
		ClientId: jsii.String("..."),
		ClientSecret: awscdk.SecretValue_SecretsManager(jsii.String("...")),
		Issuer: jsii.String("..."),
		TokenEndpoint: jsii.String("..."),
		UserInfoEndpoint: jsii.String("..."),

		// Next
		Next: elbv2.ListenerAction_Forward([]IApplicationTargetGroup{
			myTargetGroup,
		}),
	}),
})

Here's an example of using JWT authentication for service-to-service communication:

Note: JWT authentication requires an HTTPS listener. If you attempt to use it with an HTTP listener, a validation error will be thrown.

ts
declare const lb: elbv2.ApplicationLoadBalancer;
declare const certificate: elbv2.IListenerCertificate;
declare const myTargetGroup: elbv2.ApplicationTargetGroup;

// JWT authentication requires HTTPS
const listener = lb.addListener('Listener', {
  protocol: elbv2.ApplicationProtocol.HTTPS,
  port: 443,
  certificates: [certificate],
  defaultAction: elbv2.ListenerAction.authenticateJwt({
    issuer: 'https://issuer.example.com',
    jwksEndpoint: 'https://issuer.example.com/.well-known/jwks.json',
    next: elbv2.ListenerAction.forward([myTargetGroup]),
  }),
});
python
# lb: elbv2.ApplicationLoadBalancer
# certificate: elbv2.IListenerCertificate
# my_target_group: elbv2.ApplicationTargetGroup


# JWT authentication requires HTTPS
listener = lb.add_listener("Listener",
    protocol=elbv2.ApplicationProtocol.HTTPS,
    port=443,
    certificates=[certificate],
    default_action=elbv2.ListenerAction.authenticate_jwt(
        issuer="https://issuer.example.com",
        jwks_endpoint="https://issuer.example.com/.well-known/jwks.json",
        next=elbv2.ListenerAction.forward([my_target_group])
    )
)
java
ApplicationLoadBalancer lb;
IListenerCertificate certificate;
ApplicationTargetGroup myTargetGroup;


// JWT authentication requires HTTPS
ApplicationListener listener = lb.addListener("Listener", BaseApplicationListenerProps.builder()
        .protocol(ApplicationProtocol.HTTPS)
        .port(443)
        .certificates(List.of(certificate))
        .defaultAction(ListenerAction.authenticateJwt(AuthenticateJwtOptions.builder()
                .issuer("https://issuer.example.com")
                .jwksEndpoint("https://issuer.example.com/.well-known/jwks.json")
                .next(ListenerAction.forward(List.of(myTargetGroup)))
                .build()))
        .build());
csharp
ApplicationLoadBalancer lb;
IListenerCertificate certificate;
ApplicationTargetGroup myTargetGroup;


// JWT authentication requires HTTPS
var listener = lb.AddListener("Listener", new BaseApplicationListenerProps {
    Protocol = ApplicationProtocol.HTTPS,
    Port = 443,
    Certificates = new [] { certificate },
    DefaultAction = ListenerAction.AuthenticateJwt(new AuthenticateJwtOptions {
        Issuer = "https://issuer.example.com",
        JwksEndpoint = "https://issuer.example.com/.well-known/jwks.json",
        Next = ListenerAction.Forward(new [] { myTargetGroup })
    })
});
go
var lb ApplicationLoadBalancer
var certificate IListenerCertificate
var myTargetGroup ApplicationTargetGroup


// JWT authentication requires HTTPS
listener := lb.AddListener(jsii.String("Listener"), &BaseApplicationListenerProps{
	Protocol: elbv2.ApplicationProtocol_HTTPS,
	Port: jsii.Number(443),
	Certificates: []IListenerCertificate{
		certificate,
	},
	DefaultAction: elbv2.ListenerAction_AuthenticateJwt(&AuthenticateJwtOptions{
		Issuer: jsii.String("https://issuer.example.com"),
		JwksEndpoint: jsii.String("https://issuer.example.com/.well-known/jwks.json"),
		Next: elbv2.ListenerAction_Forward([]IApplicationTargetGroup{
			myTargetGroup,
		}),
	}),
})

If you just want to redirect all incoming traffic on one port to another port, you can use the following code:

ts
declare const lb: elbv2.ApplicationLoadBalancer;

lb.addRedirect({
  sourceProtocol: elbv2.ApplicationProtocol.HTTPS,
  sourcePort: 8443,
  targetProtocol: elbv2.ApplicationProtocol.HTTP,
  targetPort: 8080,
});
python
# lb: elbv2.ApplicationLoadBalancer


lb.add_redirect(
    source_protocol=elbv2.ApplicationProtocol.HTTPS,
    source_port=8443,
    target_protocol=elbv2.ApplicationProtocol.HTTP,
    target_port=8080
)
java
ApplicationLoadBalancer lb;


lb.addRedirect(ApplicationLoadBalancerRedirectConfig.builder()
        .sourceProtocol(ApplicationProtocol.HTTPS)
        .sourcePort(8443)
        .targetProtocol(ApplicationProtocol.HTTP)
        .targetPort(8080)
        .build());
csharp
ApplicationLoadBalancer lb;


lb.AddRedirect(new ApplicationLoadBalancerRedirectConfig {
    SourceProtocol = ApplicationProtocol.HTTPS,
    SourcePort = 8443,
    TargetProtocol = ApplicationProtocol.HTTP,
    TargetPort = 8080
});
go
var lb ApplicationLoadBalancer


lb.AddRedirect(&ApplicationLoadBalancerRedirectConfig{
	SourceProtocol: elbv2.ApplicationProtocol_HTTPS,
	SourcePort: jsii.Number(8443),
	TargetProtocol: elbv2.ApplicationProtocol_HTTP,
	TargetPort: jsii.Number(8080),
})

If you do not provide any options for this method, it redirects HTTP port 80 to HTTPS port 443.

By default all ingress traffic will be allowed on the source port. If you want to be more selective with your ingress rules then set open: false and use the listener's connections object to selectively grant access to the listener.

Note: The path parameter must start with a /.

Application Load Balancer attributes ​

You can modify attributes of Application Load Balancers:

ts
declare const vpc: ec2.Vpc;

const lb = new elbv2.ApplicationLoadBalancer(this, 'LB', {
  vpc,
  internetFacing: true,

  // Whether HTTP/2 is enabled
  http2Enabled: false,

  // The idle timeout value, in seconds
  idleTimeout: Duration.seconds(1000),

  // Whether HTTP headers with header fields that are not valid
  // are removed by the load balancer (true), or routed to targets
  dropInvalidHeaderFields: true,

  // How the load balancer handles requests that might
  // pose a security risk to your application
  desyncMitigationMode: elbv2.DesyncMitigationMode.DEFENSIVE,

  // The type of IP addresses to use.
  ipAddressType: elbv2.IpAddressType.IPV4,

  // The duration of client keep-alive connections
  clientKeepAlive: Duration.seconds(500),

  // Whether cross-zone load balancing is enabled.
  crossZoneEnabled: true,

  // Whether the load balancer blocks traffic through the Internet Gateway (IGW).
  denyAllIgwTraffic: false,

  // Whether to preserve host header in the request to the target
  preserveHostHeader: true,

  // Whether to add the TLS information header to the request
  xAmznTlsVersionAndCipherSuiteHeaders: true,

  // Whether the X-Forwarded-For header should preserve the source port
  preserveXffClientPort: true,

  // The processing mode for X-Forwarded-For headers
  xffHeaderProcessingMode: elbv2.XffHeaderProcessingMode.APPEND,

  // Whether to allow a load balancer to route requests to targets if it is unable to forward the request to AWS WAF.
  wafFailOpen: true,
});
python
# vpc: ec2.Vpc


lb = elbv2.ApplicationLoadBalancer(self, "LB",
    vpc=vpc,
    internet_facing=True,

    # Whether HTTP/2 is enabled
    http2_enabled=False,

    # The idle timeout value, in seconds
    idle_timeout=Duration.seconds(1000),

    # Whether HTTP headers with header fields that are not valid
    # are removed by the load balancer (true), or routed to targets
    drop_invalid_header_fields=True,

    # How the load balancer handles requests that might
    # pose a security risk to your application
    desync_mitigation_mode=elbv2.DesyncMitigationMode.DEFENSIVE,

    # The type of IP addresses to use.
    ip_address_type=elbv2.IpAddressType.IPV4,

    # The duration of client keep-alive connections
    client_keep_alive=Duration.seconds(500),

    # Whether cross-zone load balancing is enabled.
    cross_zone_enabled=True,

    # Whether the load balancer blocks traffic through the Internet Gateway (IGW).
    deny_all_igw_traffic=False,

    # Whether to preserve host header in the request to the target
    preserve_host_header=True,

    # Whether to add the TLS information header to the request
    x_amzn_tls_version_and_cipher_suite_headers=True,

    # Whether the X-Forwarded-For header should preserve the source port
    preserve_xff_client_port=True,

    # The processing mode for X-Forwarded-For headers
    xff_header_processing_mode=elbv2.XffHeaderProcessingMode.APPEND,

    # Whether to allow a load balancer to route requests to targets if it is unable to forward the request to AWS WAF.
    waf_fail_open=True
)
java
Vpc vpc;


ApplicationLoadBalancer lb = ApplicationLoadBalancer.Builder.create(this, "LB")
        .vpc(vpc)
        .internetFacing(true)

        // Whether HTTP/2 is enabled
        .http2Enabled(false)

        // The idle timeout value, in seconds
        .idleTimeout(Duration.seconds(1000))

        // Whether HTTP headers with header fields that are not valid
        // are removed by the load balancer (true), or routed to targets
        .dropInvalidHeaderFields(true)

        // How the load balancer handles requests that might
        // pose a security risk to your application
        .desyncMitigationMode(DesyncMitigationMode.DEFENSIVE)

        // The type of IP addresses to use.
        .ipAddressType(IpAddressType.IPV4)

        // The duration of client keep-alive connections
        .clientKeepAlive(Duration.seconds(500))

        // Whether cross-zone load balancing is enabled.
        .crossZoneEnabled(true)

        // Whether the load balancer blocks traffic through the Internet Gateway (IGW).
        .denyAllIgwTraffic(false)

        // Whether to preserve host header in the request to the target
        .preserveHostHeader(true)

        // Whether to add the TLS information header to the request
        .xAmznTlsVersionAndCipherSuiteHeaders(true)

        // Whether the X-Forwarded-For header should preserve the source port
        .preserveXffClientPort(true)

        // The processing mode for X-Forwarded-For headers
        .xffHeaderProcessingMode(XffHeaderProcessingMode.APPEND)

        // Whether to allow a load balancer to route requests to targets if it is unable to forward the request to AWS WAF.
        .wafFailOpen(true)
        .build();
csharp
Vpc vpc;


var lb = new ApplicationLoadBalancer(this, "LB", new ApplicationLoadBalancerProps {
    Vpc = vpc,
    InternetFacing = true,

    // Whether HTTP/2 is enabled
    Http2Enabled = false,

    // The idle timeout value, in seconds
    IdleTimeout = Duration.Seconds(1000),

    // Whether HTTP headers with header fields that are not valid
    // are removed by the load balancer (true), or routed to targets
    DropInvalidHeaderFields = true,

    // How the load balancer handles requests that might
    // pose a security risk to your application
    DesyncMitigationMode = DesyncMitigationMode.DEFENSIVE,

    // The type of IP addresses to use.
    IpAddressType = IpAddressType.IPV4,

    // The duration of client keep-alive connections
    ClientKeepAlive = Duration.Seconds(500),

    // Whether cross-zone load balancing is enabled.
    CrossZoneEnabled = true,

    // Whether the load balancer blocks traffic through the Internet Gateway (IGW).
    DenyAllIgwTraffic = false,

    // Whether to preserve host header in the request to the target
    PreserveHostHeader = true,

    // Whether to add the TLS information header to the request
    XAmznTlsVersionAndCipherSuiteHeaders = true,

    // Whether the X-Forwarded-For header should preserve the source port
    PreserveXffClientPort = true,

    // The processing mode for X-Forwarded-For headers
    XffHeaderProcessingMode = XffHeaderProcessingMode.APPEND,

    // Whether to allow a load balancer to route requests to targets if it is unable to forward the request to AWS WAF.
    WafFailOpen = true
});
go
var vpc Vpc


lb := elbv2.NewApplicationLoadBalancer(this, jsii.String("LB"), &ApplicationLoadBalancerProps{
	Vpc: Vpc,
	InternetFacing: jsii.Boolean(true),

	// Whether HTTP/2 is enabled
	Http2Enabled: jsii.Boolean(false),

	// The idle timeout value, in seconds
	IdleTimeout: awscdk.Duration_Seconds(jsii.Number(1000)),

	// Whether HTTP headers with header fields that are not valid
	// are removed by the load balancer (true), or routed to targets
	DropInvalidHeaderFields: jsii.Boolean(true),

	// How the load balancer handles requests that might
	// pose a security risk to your application
	DesyncMitigationMode: elbv2.DesyncMitigationMode_DEFENSIVE,

	// The type of IP addresses to use.
	IpAddressType: elbv2.IpAddressType_IPV4,

	// The duration of client keep-alive connections
	ClientKeepAlive: awscdk.Duration_*Seconds(jsii.Number(500)),

	// Whether cross-zone load balancing is enabled.
	CrossZoneEnabled: jsii.Boolean(true),

	// Whether the load balancer blocks traffic through the Internet Gateway (IGW).
	DenyAllIgwTraffic: jsii.Boolean(false),

	// Whether to preserve host header in the request to the target
	PreserveHostHeader: jsii.Boolean(true),

	// Whether to add the TLS information header to the request
	XAmznTlsVersionAndCipherSuiteHeaders: jsii.Boolean(true),

	// Whether the X-Forwarded-For header should preserve the source port
	PreserveXffClientPort: jsii.Boolean(true),

	// The processing mode for X-Forwarded-For headers
	XffHeaderProcessingMode: elbv2.XffHeaderProcessingMode_APPEND,

	// Whether to allow a load balancer to route requests to targets if it is unable to forward the request to AWS WAF.
	WafFailOpen: jsii.Boolean(true),
})

For more information, see Load balancer attributes

Setting up Access Log Bucket on Application Load Balancer ​

The only server-side encryption option that's supported is Amazon S3-managed keys (SSE-S3). For more information Documentation: <https://docs.aws.amazon.com/elasticloadbalancing/latest/application/enable-access-logging.html>

ts

declare const vpc: ec2.Vpc;

const bucket = new s3.Bucket(this, 'ALBAccessLogsBucket',{
  encryption: s3.BucketEncryption.S3_MANAGED,
  });

const lb = new elbv2.ApplicationLoadBalancer(this, 'LB', { vpc });
lb.logAccessLogs(bucket);
python
# vpc: ec2.Vpc


bucket = s3.Bucket(self, "ALBAccessLogsBucket",
    encryption=s3.BucketEncryption.S3_MANAGED
)

lb = elbv2.ApplicationLoadBalancer(self, "LB", vpc=vpc)
lb.log_access_logs(bucket)
java
Vpc vpc;


Bucket bucket = Bucket.Builder.create(this, "ALBAccessLogsBucket")
        .encryption(BucketEncryption.S3_MANAGED)
        .build();

ApplicationLoadBalancer lb = ApplicationLoadBalancer.Builder.create(this, "LB").vpc(vpc).build();
lb.logAccessLogs(bucket);
csharp
Vpc vpc;


var bucket = new Bucket(this, "ALBAccessLogsBucket", new BucketProps {
    Encryption = BucketEncryption.S3_MANAGED
});

var lb = new ApplicationLoadBalancer(this, "LB", new ApplicationLoadBalancerProps { Vpc = vpc });
lb.LogAccessLogs(bucket);
go
var vpc Vpc


bucket := s3.NewBucket(this, jsii.String("ALBAccessLogsBucket"), &BucketProps{
	Encryption: s3.BucketEncryption_S3_MANAGED,
})

lb := elbv2.NewApplicationLoadBalancer(this, jsii.String("LB"), &ApplicationLoadBalancerProps{
	Vpc: Vpc,
})
lb.LogAccessLogs(bucket)

Setting up Connection Log Bucket on Application Load Balancer ​

Like access log bucket, the only server-side encryption option that's supported is Amazon S3-managed keys (SSE-S3). For more information Documentation: <https://docs.aws.amazon.com/elasticloadbalancing/latest/application/enable-connection-logging.html>

ts
declare const vpc: ec2.Vpc;

const bucket = new s3.Bucket(this, 'ALBConnectionLogsBucket',{
  encryption: s3.BucketEncryption.S3_MANAGED,
});

const lb = new elbv2.ApplicationLoadBalancer(this, 'LB', { vpc });
lb.logConnectionLogs(bucket);
python
# vpc: ec2.Vpc


bucket = s3.Bucket(self, "ALBConnectionLogsBucket",
    encryption=s3.BucketEncryption.S3_MANAGED
)

lb = elbv2.ApplicationLoadBalancer(self, "LB", vpc=vpc)
lb.log_connection_logs(bucket)
java
Vpc vpc;


Bucket bucket = Bucket.Builder.create(this, "ALBConnectionLogsBucket")
        .encryption(BucketEncryption.S3_MANAGED)
        .build();

ApplicationLoadBalancer lb = ApplicationLoadBalancer.Builder.create(this, "LB").vpc(vpc).build();
lb.logConnectionLogs(bucket);
csharp
Vpc vpc;


var bucket = new Bucket(this, "ALBConnectionLogsBucket", new BucketProps {
    Encryption = BucketEncryption.S3_MANAGED
});

var lb = new ApplicationLoadBalancer(this, "LB", new ApplicationLoadBalancerProps { Vpc = vpc });
lb.LogConnectionLogs(bucket);
go
var vpc Vpc


bucket := s3.NewBucket(this, jsii.String("ALBConnectionLogsBucket"), &BucketProps{
	Encryption: s3.BucketEncryption_S3_MANAGED,
})

lb := elbv2.NewApplicationLoadBalancer(this, jsii.String("LB"), &ApplicationLoadBalancerProps{
	Vpc: Vpc,
})
lb.LogConnectionLogs(bucket)

Dualstack Application Load Balancer ​

You can create a dualstack Network Load Balancer using the ipAddressType property:

ts
declare const vpc: ec2.Vpc;

const lb = new elbv2.ApplicationLoadBalancer(this, 'LB', {
  vpc,
  ipAddressType: elbv2.IpAddressType.DUAL_STACK,
});
python
# vpc: ec2.Vpc


lb = elbv2.ApplicationLoadBalancer(self, "LB",
    vpc=vpc,
    ip_address_type=elbv2.IpAddressType.DUAL_STACK
)
java
Vpc vpc;


ApplicationLoadBalancer lb = ApplicationLoadBalancer.Builder.create(this, "LB")
        .vpc(vpc)
        .ipAddressType(IpAddressType.DUAL_STACK)
        .build();
csharp
Vpc vpc;


var lb = new ApplicationLoadBalancer(this, "LB", new ApplicationLoadBalancerProps {
    Vpc = vpc,
    IpAddressType = IpAddressType.DUAL_STACK
});
go
var vpc Vpc


lb := elbv2.NewApplicationLoadBalancer(this, jsii.String("LB"), &ApplicationLoadBalancerProps{
	Vpc: Vpc,
	IpAddressType: elbv2.IpAddressType_DUAL_STACK,
})

By setting DUAL_STACK_WITHOUT_PUBLIC_IPV4, you can provision load balancers without public IPv4s:

ts
declare const vpc: ec2.Vpc;

const lb = new elbv2.ApplicationLoadBalancer(this, 'LB', {
  vpc,
  internetFacing: true,
  ipAddressType: elbv2.IpAddressType.DUAL_STACK_WITHOUT_PUBLIC_IPV4,
});
python
# vpc: ec2.Vpc


lb = elbv2.ApplicationLoadBalancer(self, "LB",
    vpc=vpc,
    internet_facing=True,
    ip_address_type=elbv2.IpAddressType.DUAL_STACK_WITHOUT_PUBLIC_IPV4
)
java
Vpc vpc;


ApplicationLoadBalancer lb = ApplicationLoadBalancer.Builder.create(this, "LB")
        .vpc(vpc)
        .internetFacing(true)
        .ipAddressType(IpAddressType.DUAL_STACK_WITHOUT_PUBLIC_IPV4)
        .build();
csharp
Vpc vpc;


var lb = new ApplicationLoadBalancer(this, "LB", new ApplicationLoadBalancerProps {
    Vpc = vpc,
    InternetFacing = true,
    IpAddressType = IpAddressType.DUAL_STACK_WITHOUT_PUBLIC_IPV4
});
go
var vpc Vpc


lb := elbv2.NewApplicationLoadBalancer(this, jsii.String("LB"), &ApplicationLoadBalancerProps{
	Vpc: Vpc,
	InternetFacing: jsii.Boolean(true),
	IpAddressType: elbv2.IpAddressType_DUAL_STACK_WITHOUT_PUBLIC_IPV4,
})

Defining a reserved Application Load Balancer Capacity Unit (LCU) ​

You can define a reserved LCU for your Application Load Balancer. To reserve an LCU, you must specify a minimumCapacityUnit.

ts
declare const vpc: ec2.Vpc;

const lb = new elbv2.ApplicationLoadBalancer(this, 'LB', {
  vpc,
  // Valid value is between 100 and 1500.
  minimumCapacityUnit: 100,
});
python
# vpc: ec2.Vpc


lb = elbv2.ApplicationLoadBalancer(self, "LB",
    vpc=vpc,
    # Valid value is between 100 and 1500.
    minimum_capacity_unit=100
)
java
Vpc vpc;


ApplicationLoadBalancer lb = ApplicationLoadBalancer.Builder.create(this, "LB")
        .vpc(vpc)
        // Valid value is between 100 and 1500.
        .minimumCapacityUnit(100)
        .build();
csharp
Vpc vpc;


var lb = new ApplicationLoadBalancer(this, "LB", new ApplicationLoadBalancerProps {
    Vpc = vpc,
    // Valid value is between 100 and 1500.
    MinimumCapacityUnit = 100
});
go
var vpc Vpc


lb := elbv2.NewApplicationLoadBalancer(this, jsii.String("LB"), &ApplicationLoadBalancerProps{
	Vpc: Vpc,
	// Valid value is between 100 and 1500.
	MinimumCapacityUnit: jsii.Number(100),
})

Defining a Network Load Balancer ​

Network Load Balancers are defined in a similar way to Application Load Balancers:

ts
declare const vpc: ec2.Vpc;
declare const asg: autoscaling.AutoScalingGroup;

// Create the load balancer in a VPC. 'internetFacing' is 'false'
// by default, which creates an internal load balancer.
const lb = new elbv2.NetworkLoadBalancer(this, 'LB', {
  vpc,
  internetFacing: true,
});

// Add a listener on a particular port.
const listener = lb.addListener('Listener', {
  port: 443,
});

// Add targets on a particular port.
listener.addTargets('AppFleet', {
  port: 443,
  targets: [asg]
});
python
# vpc: ec2.Vpc
# asg: autoscaling.AutoScalingGroup


# Create the load balancer in a VPC. 'internetFacing' is 'false'
# by default, which creates an internal load balancer.
lb = elbv2.NetworkLoadBalancer(self, "LB",
    vpc=vpc,
    internet_facing=True
)

# Add a listener on a particular port.
listener = lb.add_listener("Listener",
    port=443
)

# Add targets on a particular port.
listener.add_targets("AppFleet",
    port=443,
    targets=[asg]
)
java
Vpc vpc;
AutoScalingGroup asg;


// Create the load balancer in a VPC. 'internetFacing' is 'false'
// by default, which creates an internal load balancer.
NetworkLoadBalancer lb = NetworkLoadBalancer.Builder.create(this, "LB")
        .vpc(vpc)
        .internetFacing(true)
        .build();

// Add a listener on a particular port.
NetworkListener listener = lb.addListener("Listener", BaseNetworkListenerProps.builder()
        .port(443)
        .build());

// Add targets on a particular port.
listener.addTargets("AppFleet", AddNetworkTargetsProps.builder()
        .port(443)
        .targets(List.of(asg))
        .build());
csharp
Vpc vpc;
AutoScalingGroup asg;


// Create the load balancer in a VPC. 'internetFacing' is 'false'
// by default, which creates an internal load balancer.
var lb = new NetworkLoadBalancer(this, "LB", new NetworkLoadBalancerProps {
    Vpc = vpc,
    InternetFacing = true
});

// Add a listener on a particular port.
var listener = lb.AddListener("Listener", new BaseNetworkListenerProps {
    Port = 443
});

// Add targets on a particular port.
listener.AddTargets("AppFleet", new AddNetworkTargetsProps {
    Port = 443,
    Targets = new [] { asg }
});
go
var vpc Vpc
var asg AutoScalingGroup


// Create the load balancer in a VPC. 'internetFacing' is 'false'
// by default, which creates an internal load balancer.
lb := elbv2.NewNetworkLoadBalancer(this, jsii.String("LB"), &NetworkLoadBalancerProps{
	Vpc: Vpc,
	InternetFacing: jsii.Boolean(true),
})

// Add a listener on a particular port.
listener := lb.AddListener(jsii.String("Listener"), &BaseNetworkListenerProps{
	Port: jsii.Number(443),
})

// Add targets on a particular port.
listener.AddTargets(jsii.String("AppFleet"), &AddNetworkTargetsProps{
	Port: jsii.Number(443),
	Targets: []INetworkLoadBalancerTarget{
		asg,
	},
})

Security Groups for Network Load Balancer ​

By default, Network Load Balancers (NLB) have a security group associated with them. This is controlled by the feature flag @aws-cdk/aws-elasticloadbalancingv2:networkLoadBalancerWithSecurityGroupByDefault. When this flag is enabled (the default for new projects), a security group will be automatically created and attached to the NLB unless you explicitly provide your own security groups via the securityGroups property.

If you wish to create an NLB without any security groups, you can set the disableSecurityGroups property to true. When this property is set, no security group will be associated with the NLB, regardless of the feature flag.

ts
declare const vpc: ec2.IVpc;

const nlb = new elbv2.NetworkLoadBalancer(this, 'LB', {
  vpc,
  // To disable security groups for this NLB
  disableSecurityGroups: true,
});
python
# vpc: ec2.IVpc


nlb = elbv2.NetworkLoadBalancer(self, "LB",
    vpc=vpc,
    # To disable security groups for this NLB
    disable_security_groups=True
)
java
IVpc vpc;


NetworkLoadBalancer nlb = NetworkLoadBalancer.Builder.create(this, "LB")
        .vpc(vpc)
        // To disable security groups for this NLB
        .disableSecurityGroups(true)
        .build();
csharp
IVpc vpc;


var nlb = new NetworkLoadBalancer(this, "LB", new NetworkLoadBalancerProps {
    Vpc = vpc,
    // To disable security groups for this NLB
    DisableSecurityGroups = true
});
go
var vpc IVpc


nlb := elbv2.NewNetworkLoadBalancer(this, jsii.String("LB"), &NetworkLoadBalancerProps{
	Vpc: Vpc,
	// To disable security groups for this NLB
	DisableSecurityGroups: jsii.Boolean(true),
})

If you want to use your own security groups, provide them via the securityGroups property:

ts
declare const vpc: ec2.IVpc;
declare const sg1: ec2.ISecurityGroup;
declare const sg2: ec2.ISecurityGroup;

const nlb = new elbv2.NetworkLoadBalancer(this, 'LB', {
  vpc,
  // Provide your own security groups
  securityGroups: [sg1],
});
// Add another security group to the NLB
nlb.addSecurityGroup(sg2);
python
# vpc: ec2.IVpc
# sg1: ec2.ISecurityGroup
# sg2: ec2.ISecurityGroup


nlb = elbv2.NetworkLoadBalancer(self, "LB",
    vpc=vpc,
    # Provide your own security groups
    security_groups=[sg1]
)
# Add another security group to the NLB
nlb.add_security_group(sg2)
java
IVpc vpc;
ISecurityGroup sg1;
ISecurityGroup sg2;


NetworkLoadBalancer nlb = NetworkLoadBalancer.Builder.create(this, "LB")
        .vpc(vpc)
        // Provide your own security groups
        .securityGroups(List.of(sg1))
        .build();
// Add another security group to the NLB
nlb.addSecurityGroup(sg2);
csharp
IVpc vpc;
ISecurityGroup sg1;
ISecurityGroup sg2;


var nlb = new NetworkLoadBalancer(this, "LB", new NetworkLoadBalancerProps {
    Vpc = vpc,
    // Provide your own security groups
    SecurityGroups = new [] { sg1 }
});
// Add another security group to the NLB
nlb.AddSecurityGroup(sg2);
go
var vpc IVpc
var sg1 ISecurityGroup
var sg2 ISecurityGroup


nlb := elbv2.NewNetworkLoadBalancer(this, jsii.String("LB"), &NetworkLoadBalancerProps{
	Vpc: Vpc,
	// Provide your own security groups
	SecurityGroups: []ISecurityGroup{
		sg1,
	},
})
// Add another security group to the NLB
nlb.AddSecurityGroup(sg2)

You can indicate whether to evaluate inbound security group rules for traffic sent to a Network Load Balancer through AWS PrivateLink. The evaluation is enabled by default.

ts
declare const vpc: ec2.Vpc;

const nlb = new elbv2.NetworkLoadBalancer(this, 'LB', {
  vpc,
  enforceSecurityGroupInboundRulesOnPrivateLinkTraffic: true,
});
python
# vpc: ec2.Vpc


nlb = elbv2.NetworkLoadBalancer(self, "LB",
    vpc=vpc,
    enforce_security_group_inbound_rules_on_private_link_traffic=True
)
java
Vpc vpc;


NetworkLoadBalancer nlb = NetworkLoadBalancer.Builder.create(this, "LB")
        .vpc(vpc)
        .enforceSecurityGroupInboundRulesOnPrivateLinkTraffic(true)
        .build();
csharp
Vpc vpc;


var nlb = new NetworkLoadBalancer(this, "LB", new NetworkLoadBalancerProps {
    Vpc = vpc,
    EnforceSecurityGroupInboundRulesOnPrivateLinkTraffic = true
});
go
var vpc Vpc


nlb := elbv2.NewNetworkLoadBalancer(this, jsii.String("LB"), &NetworkLoadBalancerProps{
	Vpc: Vpc,
	EnforceSecurityGroupInboundRulesOnPrivateLinkTraffic: jsii.Boolean(true),
})

One thing to keep in mind is that network load balancers do not have security groups, and no automatic security group configuration is done for you. You will have to configure the security groups of the target yourself to allow traffic by clients and/or load balancer instances, depending on your target types. See Target Groups for your Network Load Balancers and Register targets with your Target Group for more information.

Dualstack Network Load Balancer ​

You can create a dualstack Network Load Balancer using the ipAddressType property:

ts
declare const vpc: ec2.Vpc;

const lb = new elbv2.NetworkLoadBalancer(this, 'LB', {
  vpc,
  ipAddressType: elbv2.IpAddressType.DUAL_STACK,
});
python
# vpc: ec2.Vpc


lb = elbv2.NetworkLoadBalancer(self, "LB",
    vpc=vpc,
    ip_address_type=elbv2.IpAddressType.DUAL_STACK
)
java
Vpc vpc;


NetworkLoadBalancer lb = NetworkLoadBalancer.Builder.create(this, "LB")
        .vpc(vpc)
        .ipAddressType(IpAddressType.DUAL_STACK)
        .build();
csharp
Vpc vpc;


var lb = new NetworkLoadBalancer(this, "LB", new NetworkLoadBalancerProps {
    Vpc = vpc,
    IpAddressType = IpAddressType.DUAL_STACK
});
go
var vpc Vpc


lb := elbv2.NewNetworkLoadBalancer(this, jsii.String("LB"), &NetworkLoadBalancerProps{
	Vpc: Vpc,
	IpAddressType: elbv2.IpAddressType_DUAL_STACK,
})

You can configure whether to use an IPv6 prefix from each subnet for source NAT by setting enablePrefixForIpv6SourceNat to true. This must be enabled if you want to create a dualstack Network Load Balancer with a listener that uses UDP protocol.

ts
declare const vpc: ec2.Vpc;

const lb = new elbv2.NetworkLoadBalancer(this, 'LB', {
  vpc,
  ipAddressType: elbv2.IpAddressType.DUAL_STACK,
  enablePrefixForIpv6SourceNat: true,
});

const listener = lb.addListener('Listener', {
  port: 1229,
  protocol: elbv2.Protocol.UDP,
});
python
# vpc: ec2.Vpc


lb = elbv2.NetworkLoadBalancer(self, "LB",
    vpc=vpc,
    ip_address_type=elbv2.IpAddressType.DUAL_STACK,
    enable_prefix_for_ipv6_source_nat=True
)

listener = lb.add_listener("Listener",
    port=1229,
    protocol=elbv2.Protocol.UDP
)
java
Vpc vpc;


NetworkLoadBalancer lb = NetworkLoadBalancer.Builder.create(this, "LB")
        .vpc(vpc)
        .ipAddressType(IpAddressType.DUAL_STACK)
        .enablePrefixForIpv6SourceNat(true)
        .build();

NetworkListener listener = lb.addListener("Listener", BaseNetworkListenerProps.builder()
        .port(1229)
        .protocol(Protocol.UDP)
        .build());
csharp
Vpc vpc;


var lb = new NetworkLoadBalancer(this, "LB", new NetworkLoadBalancerProps {
    Vpc = vpc,
    IpAddressType = IpAddressType.DUAL_STACK,
    EnablePrefixForIpv6SourceNat = true
});

var listener = lb.AddListener("Listener", new BaseNetworkListenerProps {
    Port = 1229,
    Protocol = Protocol.UDP
});
go
var vpc Vpc


lb := elbv2.NewNetworkLoadBalancer(this, jsii.String("LB"), &NetworkLoadBalancerProps{
	Vpc: Vpc,
	IpAddressType: elbv2.IpAddressType_DUAL_STACK,
	EnablePrefixForIpv6SourceNat: jsii.Boolean(true),
})

listener := lb.AddListener(jsii.String("Listener"), &BaseNetworkListenerProps{
	Port: jsii.Number(1229),
	Protocol: elbv2.Protocol_UDP,
})

Configuring a subnet information for a Network Load Balancer ​

You can specify the subnets for a Network Load Balancer easily by setting the vpcSubnets property.

ts
declare const vpc: ec2.Vpc;

const lb = new elbv2.NetworkLoadBalancer(this, 'LB', {
  vpc,
  vpcSubnets: {
    subnetType: ec2.SubnetType.PRIVATE,
  },
});
python
# vpc: ec2.Vpc


lb = elbv2.NetworkLoadBalancer(self, "LB",
    vpc=vpc,
    vpc_subnets=ec2.SubnetSelection(
        subnet_type=ec2.SubnetType.PRIVATE
    )
)
java
Vpc vpc;


NetworkLoadBalancer lb = NetworkLoadBalancer.Builder.create(this, "LB")
        .vpc(vpc)
        .vpcSubnets(SubnetSelection.builder()
                .subnetType(SubnetType.PRIVATE)
                .build())
        .build();
csharp
Vpc vpc;


var lb = new NetworkLoadBalancer(this, "LB", new NetworkLoadBalancerProps {
    Vpc = vpc,
    VpcSubnets = new SubnetSelection {
        SubnetType = SubnetType.PRIVATE
    }
});
go
var vpc Vpc


lb := elbv2.NewNetworkLoadBalancer(this, jsii.String("LB"), &NetworkLoadBalancerProps{
	Vpc: Vpc,
	VpcSubnets: &SubnetSelection{
		SubnetType: ec2.SubnetType_PRIVATE,
	},
})

If you want to configure detailed information about the subnets, you can use the subnetMappings property as follows:

ts
declare const vpc: ec2.IVpc;
declare const dualstackVpc: ec2.IVpc;
declare const subnet: ec2.ISubnet;
declare const dualstackSubnet: ec2.ISubnet;
declare const cfnEip: ec2.CfnEIP;

// Internet facing Network Load Balancer with an Elastic IPv4 address
new elbv2.NetworkLoadBalancer(this, 'InternetFacingLb', {
  vpc,
  internetFacing: true,
  subnetMappings: [
    {
      subnet,
      // The allocation ID of the Elastic IP address
      allocationId: cfnEip.attrAllocationId,
    },
  ],
});

// Internal Network Load Balancer with a private IPv4 address
new elbv2.NetworkLoadBalancer(this, 'InternalLb', {
  vpc,
  internetFacing: false,
  subnetMappings: [
    {
      subnet,
      // The private IPv4 address from the subnet
      // The address must be in the subnet's CIDR range and
      // can not be configured for a internet facing Network Load Balancer.
      privateIpv4Address: '10.0.12.29',
    },
  ],
});

// Dualstack Network Load Balancer with an IPv6 address and prefix for source NAT
new elbv2.NetworkLoadBalancer(this, 'DualstackLb', {
  vpc: dualstackVpc,
  // Configure the dualstack Network Load Balancer
  ipAddressType: elbv2.IpAddressType.DUAL_STACK,
  enablePrefixForIpv6SourceNat: true,
  subnetMappings: [
    {
      subnet: dualstackSubnet,
      // The IPv6 address from the subnet
      // `ipAddresstype` must be `DUAL_STACK` or `DUAL_STACK_WITHOUT_PUBLIC_IPV4` to set the IPv6 address.
      ipv6Address: '2001:db8:1234:1a00::10',
      // The IPv6 prefix to use for source NAT
      // `enablePrefixForIpv6SourceNat` must be `true` to set `sourceNatIpv6Prefix`.
      sourceNatIpv6Prefix: elbv2.SourceNatIpv6Prefix.autoAssigned(),
    },
  ],
});
python
# vpc: ec2.IVpc
# dualstack_vpc: ec2.IVpc
# subnet: ec2.ISubnet
# dualstack_subnet: ec2.ISubnet
# cfn_eip: ec2.CfnEIP


# Internet facing Network Load Balancer with an Elastic IPv4 address
elbv2.NetworkLoadBalancer(self, "InternetFacingLb",
    vpc=vpc,
    internet_facing=True,
    subnet_mappings=[elbv2.SubnetMapping(
        subnet=subnet,
        # The allocation ID of the Elastic IP address
        allocation_id=cfn_eip.attr_allocation_id
    )
    ]
)

# Internal Network Load Balancer with a private IPv4 address
elbv2.NetworkLoadBalancer(self, "InternalLb",
    vpc=vpc,
    internet_facing=False,
    subnet_mappings=[elbv2.SubnetMapping(
        subnet=subnet,
        # The private IPv4 address from the subnet
        # The address must be in the subnet's CIDR range and
        # can not be configured for a internet facing Network Load Balancer.
        private_ipv4_address="10.0.12.29"
    )
    ]
)

# Dualstack Network Load Balancer with an IPv6 address and prefix for source NAT
elbv2.NetworkLoadBalancer(self, "DualstackLb",
    vpc=dualstack_vpc,
    # Configure the dualstack Network Load Balancer
    ip_address_type=elbv2.IpAddressType.DUAL_STACK,
    enable_prefix_for_ipv6_source_nat=True,
    subnet_mappings=[elbv2.SubnetMapping(
        subnet=dualstack_subnet,
        # The IPv6 address from the subnet
        # `ipAddresstype` must be `DUAL_STACK` or `DUAL_STACK_WITHOUT_PUBLIC_IPV4` to set the IPv6 address.
        ipv6_address="2001:db8:1234:1a00::10",
        # The IPv6 prefix to use for source NAT
        # `enablePrefixForIpv6SourceNat` must be `true` to set `sourceNatIpv6Prefix`.
        source_nat_ipv6_prefix=elbv2.SourceNatIpv6Prefix.auto_assigned()
    )
    ]
)
java
IVpc vpc;
IVpc dualstackVpc;
ISubnet subnet;
ISubnet dualstackSubnet;
CfnEIP cfnEip;


// Internet facing Network Load Balancer with an Elastic IPv4 address
// Internet facing Network Load Balancer with an Elastic IPv4 address
NetworkLoadBalancer.Builder.create(this, "InternetFacingLb")
        .vpc(vpc)
        .internetFacing(true)
        .subnetMappings(List.of(SubnetMapping.builder()
                .subnet(subnet)
                // The allocation ID of the Elastic IP address
                .allocationId(cfnEip.getAttrAllocationId())
                .build()))
        .build();

// Internal Network Load Balancer with a private IPv4 address
// Internal Network Load Balancer with a private IPv4 address
NetworkLoadBalancer.Builder.create(this, "InternalLb")
        .vpc(vpc)
        .internetFacing(false)
        .subnetMappings(List.of(SubnetMapping.builder()
                .subnet(subnet)
                // The private IPv4 address from the subnet
                // The address must be in the subnet's CIDR range and
                // can not be configured for a internet facing Network Load Balancer.
                .privateIpv4Address("10.0.12.29")
                .build()))
        .build();

// Dualstack Network Load Balancer with an IPv6 address and prefix for source NAT
// Dualstack Network Load Balancer with an IPv6 address and prefix for source NAT
NetworkLoadBalancer.Builder.create(this, "DualstackLb")
        .vpc(dualstackVpc)
        // Configure the dualstack Network Load Balancer
        .ipAddressType(IpAddressType.DUAL_STACK)
        .enablePrefixForIpv6SourceNat(true)
        .subnetMappings(List.of(SubnetMapping.builder()
                .subnet(dualstackSubnet)
                // The IPv6 address from the subnet
                // `ipAddresstype` must be `DUAL_STACK` or `DUAL_STACK_WITHOUT_PUBLIC_IPV4` to set the IPv6 address.
                .ipv6Address("2001:db8:1234:1a00::10")
                // The IPv6 prefix to use for source NAT
                // `enablePrefixForIpv6SourceNat` must be `true` to set `sourceNatIpv6Prefix`.
                .sourceNatIpv6Prefix(SourceNatIpv6Prefix.autoAssigned())
                .build()))
        .build();
csharp
IVpc vpc;
IVpc dualstackVpc;
ISubnet subnet;
ISubnet dualstackSubnet;
CfnEIP cfnEip;


// Internet facing Network Load Balancer with an Elastic IPv4 address
// Internet facing Network Load Balancer with an Elastic IPv4 address
new NetworkLoadBalancer(this, "InternetFacingLb", new NetworkLoadBalancerProps {
    Vpc = vpc,
    InternetFacing = true,
    SubnetMappings = new [] { new SubnetMapping {
        Subnet = subnet,
        // The allocation ID of the Elastic IP address
        AllocationId = cfnEip.AttrAllocationId
    } }
});

// Internal Network Load Balancer with a private IPv4 address
// Internal Network Load Balancer with a private IPv4 address
new NetworkLoadBalancer(this, "InternalLb", new NetworkLoadBalancerProps {
    Vpc = vpc,
    InternetFacing = false,
    SubnetMappings = new [] { new SubnetMapping {
        Subnet = subnet,
        // The private IPv4 address from the subnet
        // The address must be in the subnet's CIDR range and
        // can not be configured for a internet facing Network Load Balancer.
        PrivateIpv4Address = "10.0.12.29"
    } }
});

// Dualstack Network Load Balancer with an IPv6 address and prefix for source NAT
// Dualstack Network Load Balancer with an IPv6 address and prefix for source NAT
new NetworkLoadBalancer(this, "DualstackLb", new NetworkLoadBalancerProps {
    Vpc = dualstackVpc,
    // Configure the dualstack Network Load Balancer
    IpAddressType = IpAddressType.DUAL_STACK,
    EnablePrefixForIpv6SourceNat = true,
    SubnetMappings = new [] { new SubnetMapping {
        Subnet = dualstackSubnet,
        // The IPv6 address from the subnet
        // `ipAddresstype` must be `DUAL_STACK` or `DUAL_STACK_WITHOUT_PUBLIC_IPV4` to set the IPv6 address.
        Ipv6Address = "2001:db8:1234:1a00::10",
        // The IPv6 prefix to use for source NAT
        // `enablePrefixForIpv6SourceNat` must be `true` to set `sourceNatIpv6Prefix`.
        SourceNatIpv6Prefix = SourceNatIpv6Prefix.AutoAssigned()
    } }
});
go
var vpc IVpc
var dualstackVpc IVpc
var subnet ISubnet
var dualstackSubnet ISubnet
var cfnEip CfnEIP


// Internet facing Network Load Balancer with an Elastic IPv4 address
// Internet facing Network Load Balancer with an Elastic IPv4 address
elbv2.NewNetworkLoadBalancer(this, jsii.String("InternetFacingLb"), &NetworkLoadBalancerProps{
	Vpc: Vpc,
	InternetFacing: jsii.Boolean(true),
	SubnetMappings: []SubnetMapping{
		&SubnetMapping{
			Subnet: *Subnet,
			// The allocation ID of the Elastic IP address
			AllocationId: cfnEip.attrAllocationId,
		},
	},
})

// Internal Network Load Balancer with a private IPv4 address
// Internal Network Load Balancer with a private IPv4 address
elbv2.NewNetworkLoadBalancer(this, jsii.String("InternalLb"), &NetworkLoadBalancerProps{
	Vpc: Vpc,
	InternetFacing: jsii.Boolean(false),
	SubnetMappings: []SubnetMapping{
		&SubnetMapping{
			Subnet: *Subnet,
			// The private IPv4 address from the subnet
			// The address must be in the subnet's CIDR range and
			// can not be configured for a internet facing Network Load Balancer.
			PrivateIpv4Address: jsii.String("10.0.12.29"),
		},
	},
})

// Dualstack Network Load Balancer with an IPv6 address and prefix for source NAT
// Dualstack Network Load Balancer with an IPv6 address and prefix for source NAT
elbv2.NewNetworkLoadBalancer(this, jsii.String("DualstackLb"), &NetworkLoadBalancerProps{
	Vpc: dualstackVpc,
	// Configure the dualstack Network Load Balancer
	IpAddressType: elbv2.IpAddressType_DUAL_STACK,
	EnablePrefixForIpv6SourceNat: jsii.Boolean(true),
	SubnetMappings: []SubnetMapping{
		&SubnetMapping{
			Subnet: dualstackSubnet,
			// The IPv6 address from the subnet
			// `ipAddresstype` must be `DUAL_STACK` or `DUAL_STACK_WITHOUT_PUBLIC_IPV4` to set the IPv6 address.
			Ipv6Address: jsii.String("2001:db8:1234:1a00::10"),
			// The IPv6 prefix to use for source NAT
			// `enablePrefixForIpv6SourceNat` must be `true` to set `sourceNatIpv6Prefix`.
			SourceNatIpv6Prefix: elbv2.SourceNatIpv6Prefix_AutoAssigned(),
		},
	},
})

Network Load Balancer attributes ​

You can modify attributes of Network Load Balancers:

ts
declare const vpc: ec2.Vpc;

const lb = new elbv2.NetworkLoadBalancer(this, 'LB', {
  vpc,
  // Whether deletion protection is enabled.
  deletionProtection: true,

  // Whether cross-zone load balancing is enabled.
  crossZoneEnabled: true,

  // Whether the load balancer blocks traffic through the Internet Gateway (IGW).
  denyAllIgwTraffic: false,

  // Indicates how traffic is distributed among the load balancer Availability Zones.
  clientRoutingPolicy: elbv2.ClientRoutingPolicy.AVAILABILITY_ZONE_AFFINITY,

  // Indicates whether zonal shift is enabled.
  zonalShift: true,
});
python
# vpc: ec2.Vpc


lb = elbv2.NetworkLoadBalancer(self, "LB",
    vpc=vpc,
    # Whether deletion protection is enabled.
    deletion_protection=True,

    # Whether cross-zone load balancing is enabled.
    cross_zone_enabled=True,

    # Whether the load balancer blocks traffic through the Internet Gateway (IGW).
    deny_all_igw_traffic=False,

    # Indicates how traffic is distributed among the load balancer Availability Zones.
    client_routing_policy=elbv2.ClientRoutingPolicy.AVAILABILITY_ZONE_AFFINITY,

    # Indicates whether zonal shift is enabled.
    zonal_shift=True
)
java
Vpc vpc;


NetworkLoadBalancer lb = NetworkLoadBalancer.Builder.create(this, "LB")
        .vpc(vpc)
        // Whether deletion protection is enabled.
        .deletionProtection(true)

        // Whether cross-zone load balancing is enabled.
        .crossZoneEnabled(true)

        // Whether the load balancer blocks traffic through the Internet Gateway (IGW).
        .denyAllIgwTraffic(false)

        // Indicates how traffic is distributed among the load balancer Availability Zones.
        .clientRoutingPolicy(ClientRoutingPolicy.AVAILABILITY_ZONE_AFFINITY)

        // Indicates whether zonal shift is enabled.
        .zonalShift(true)
        .build();
csharp
Vpc vpc;


var lb = new NetworkLoadBalancer(this, "LB", new NetworkLoadBalancerProps {
    Vpc = vpc,
    // Whether deletion protection is enabled.
    DeletionProtection = true,

    // Whether cross-zone load balancing is enabled.
    CrossZoneEnabled = true,

    // Whether the load balancer blocks traffic through the Internet Gateway (IGW).
    DenyAllIgwTraffic = false,

    // Indicates how traffic is distributed among the load balancer Availability Zones.
    ClientRoutingPolicy = ClientRoutingPolicy.AVAILABILITY_ZONE_AFFINITY,

    // Indicates whether zonal shift is enabled.
    ZonalShift = true
});
go
var vpc Vpc


lb := elbv2.NewNetworkLoadBalancer(this, jsii.String("LB"), &NetworkLoadBalancerProps{
	Vpc: Vpc,
	// Whether deletion protection is enabled.
	DeletionProtection: jsii.Boolean(true),

	// Whether cross-zone load balancing is enabled.
	CrossZoneEnabled: jsii.Boolean(true),

	// Whether the load balancer blocks traffic through the Internet Gateway (IGW).
	DenyAllIgwTraffic: jsii.Boolean(false),

	// Indicates how traffic is distributed among the load balancer Availability Zones.
	ClientRoutingPolicy: elbv2.ClientRoutingPolicy_AVAILABILITY_ZONE_AFFINITY,

	// Indicates whether zonal shift is enabled.
	ZonalShift: jsii.Boolean(true),
})

Network Load Balancer Listener attributes ​

You can modify attributes of Network Load Balancer Listener:

ts
declare const lb: elbv2.NetworkLoadBalancer;
declare const group: elbv2.NetworkTargetGroup;

const listener = lb.addListener('Listener', {
  port: 80,
  defaultAction: elbv2.NetworkListenerAction.forward([group]),

  // The tcp idle timeout value. The valid range is 60-6000 seconds. The default is 350 seconds.
  tcpIdleTimeout: Duration.seconds(100),
});
python
# lb: elbv2.NetworkLoadBalancer
# group: elbv2.NetworkTargetGroup


listener = lb.add_listener("Listener",
    port=80,
    default_action=elbv2.NetworkListenerAction.forward([group]),

    # The tcp idle timeout value. The valid range is 60-6000 seconds. The default is 350 seconds.
    tcp_idle_timeout=Duration.seconds(100)
)
java
NetworkLoadBalancer lb;
NetworkTargetGroup group;


NetworkListener listener = lb.addListener("Listener", BaseNetworkListenerProps.builder()
        .port(80)
        .defaultAction(NetworkListenerAction.forward(List.of(group)))

        // The tcp idle timeout value. The valid range is 60-6000 seconds. The default is 350 seconds.
        .tcpIdleTimeout(Duration.seconds(100))
        .build());
csharp
NetworkLoadBalancer lb;
NetworkTargetGroup group;


var listener = lb.AddListener("Listener", new BaseNetworkListenerProps {
    Port = 80,
    DefaultAction = NetworkListenerAction.Forward(new [] { group }),

    // The tcp idle timeout value. The valid range is 60-6000 seconds. The default is 350 seconds.
    TcpIdleTimeout = Duration.Seconds(100)
});
go
var lb NetworkLoadBalancer
var group NetworkTargetGroup


listener := lb.AddListener(jsii.String("Listener"), &BaseNetworkListenerProps{
	Port: jsii.Number(80),
	DefaultAction: elbv2.NetworkListenerAction_Forward([]INetworkTargetGroup{
		group,
	}),

	// The tcp idle timeout value. The valid range is 60-6000 seconds. The default is 350 seconds.
	TcpIdleTimeout: awscdk.Duration_Seconds(jsii.Number(100)),
})

Network Load Balancer and EC2 IConnectable interface ​

Network Load Balancer implements EC2 IConnectable and exposes connections property. EC2 Connections allows manage the allowed network connections for constructs with Security Groups. This class makes it easy to allow network connections to and from security groups, and between security groups individually. One thing to keep in mind is that network load balancers do not have security groups, and no automatic security group configuration is done for you. You will have to configure the security groups of the target yourself to allow traffic by clients and/or load balancer instances, depending on your target types.

ts
declare const vpc: ec2.Vpc;
declare const sg1: ec2.ISecurityGroup;
declare const sg2: ec2.ISecurityGroup;

const lb = new elbv2.NetworkLoadBalancer(this, 'LB', {
  vpc,
  internetFacing: true,
  securityGroups: [sg1],
});
lb.addSecurityGroup(sg2);
lb.connections.allowFromAnyIpv4(ec2.Port.tcp(80));
python
# vpc: ec2.Vpc
# sg1: ec2.ISecurityGroup
# sg2: ec2.ISecurityGroup


lb = elbv2.NetworkLoadBalancer(self, "LB",
    vpc=vpc,
    internet_facing=True,
    security_groups=[sg1]
)
lb.add_security_group(sg2)
lb.connections.allow_from_any_ipv4(ec2.Port.tcp(80))
java
Vpc vpc;
ISecurityGroup sg1;
ISecurityGroup sg2;


NetworkLoadBalancer lb = NetworkLoadBalancer.Builder.create(this, "LB")
        .vpc(vpc)
        .internetFacing(true)
        .securityGroups(List.of(sg1))
        .build();
lb.addSecurityGroup(sg2);
lb.connections.allowFromAnyIpv4(Port.tcp(80));
csharp
Vpc vpc;
ISecurityGroup sg1;
ISecurityGroup sg2;


var lb = new NetworkLoadBalancer(this, "LB", new NetworkLoadBalancerProps {
    Vpc = vpc,
    InternetFacing = true,
    SecurityGroups = new [] { sg1 }
});
lb.AddSecurityGroup(sg2);
lb.Connections.AllowFromAnyIpv4(Port.Tcp(80));
go
var vpc Vpc
var sg1 ISecurityGroup
var sg2 ISecurityGroup


lb := elbv2.NewNetworkLoadBalancer(this, jsii.String("LB"), &NetworkLoadBalancerProps{
	Vpc: Vpc,
	InternetFacing: jsii.Boolean(true),
	SecurityGroups: []ISecurityGroup{
		sg1,
	},
})
lb.AddSecurityGroup(sg2)
lb.Connections.AllowFromAnyIpv4(ec2.Port_Tcp(jsii.Number(80)))

Defining a reserved Network Load Balancer Capacity Unit (LCU) ​

You can define a reserved LCU for your Network Load Balancer.

When requesting a LCU reservation, convert your capacity needs from Mbps to LCUs using the conversion rate of 1 LCU to 2.2 Mbps.

To reserve an LCU, you must specify a minimumCapacityUnit.

ts
declare const vpc: ec2.Vpc;

const lb = new elbv2.NetworkLoadBalancer(this, 'LB', {
  vpc,
  minimumCapacityUnit: 5500,
});
python
# vpc: ec2.Vpc


lb = elbv2.NetworkLoadBalancer(self, "LB",
    vpc=vpc,
    minimum_capacity_unit=5500
)
java
Vpc vpc;


NetworkLoadBalancer lb = NetworkLoadBalancer.Builder.create(this, "LB")
        .vpc(vpc)
        .minimumCapacityUnit(5500)
        .build();
csharp
Vpc vpc;


var lb = new NetworkLoadBalancer(this, "LB", new NetworkLoadBalancerProps {
    Vpc = vpc,
    MinimumCapacityUnit = 5500
});
go
var vpc Vpc


lb := elbv2.NewNetworkLoadBalancer(this, jsii.String("LB"), &NetworkLoadBalancerProps{
	Vpc: Vpc,
	MinimumCapacityUnit: jsii.Number(5500),
})

Note: The minimumCapacityUnit value is evenly distributed across all active Availability Zones (AZs) for the network load balancer. The distributed value per AZ must be between 2,750 and 45,000 units.

Targets and Target Groups ​

Application and Network Load Balancers organize load balancing targets in Target Groups. If you add your balancing targets (such as AutoScalingGroups, ECS services or individual instances) to your listener directly, the appropriate TargetGroup will be automatically created for you.

If you need more control over the Target Groups created, create an instance of ApplicationTargetGroup or NetworkTargetGroup, add the members you desire, and add it to the listener by calling addTargetGroups instead of addTargets.

addTargets() will always return the Target Group it just created for you:

ts
declare const listener: elbv2.NetworkListener;
declare const asg1: autoscaling.AutoScalingGroup;
declare const asg2: autoscaling.AutoScalingGroup;

const group = listener.addTargets('AppFleet', {
  port: 443,
  targets: [asg1],
});

group.addTarget(asg2);
python
# listener: elbv2.NetworkListener
# asg1: autoscaling.AutoScalingGroup
# asg2: autoscaling.AutoScalingGroup


group = listener.add_targets("AppFleet",
    port=443,
    targets=[asg1]
)

group.add_target(asg2)
java
NetworkListener listener;
AutoScalingGroup asg1;
AutoScalingGroup asg2;


NetworkTargetGroup group = listener.addTargets("AppFleet", AddNetworkTargetsProps.builder()
        .port(443)
        .targets(List.of(asg1))
        .build());

group.addTarget(asg2);
csharp
NetworkListener listener;
AutoScalingGroup asg1;
AutoScalingGroup asg2;


var group = listener.AddTargets("AppFleet", new AddNetworkTargetsProps {
    Port = 443,
    Targets = new [] { asg1 }
});

group.AddTarget(asg2);
go
var listener NetworkListener
var asg1 AutoScalingGroup
var asg2 AutoScalingGroup


group := listener.AddTargets(jsii.String("AppFleet"), &AddNetworkTargetsProps{
	Port: jsii.Number(443),
	Targets: []INetworkLoadBalancerTarget{
		asg1,
	},
})

group.AddTarget(asg2)

Sticky sessions for your Application Load Balancer ​

By default, an Application Load Balancer routes each request independently to a registered target based on the chosen load-balancing algorithm. However, you can use the sticky session feature (also known as session affinity) to enable the load balancer to bind a user's session to a specific target. This ensures that all requests from the user during the session are sent to the same target. This feature is useful for servers that maintain state information in order to provide a continuous experience to clients. To use sticky sessions, the client must support cookies.

Application Load Balancers support both duration-based cookies (lb_cookie) and application-based cookies (app_cookie). The key to managing sticky sessions is determining how long your load balancer should consistently route the user's request to the same target. Sticky sessions are enabled at the target group level. You can use a combination of duration-based stickiness, application-based stickiness, and no stickiness across all of your target groups.

ts
declare const vpc: ec2.Vpc;

// Target group with duration-based stickiness with load-balancer generated cookie
const tg1 = new elbv2.ApplicationTargetGroup(this, 'TG1', {
  targetType: elbv2.TargetType.INSTANCE,
  port: 80,
  stickinessCookieDuration: Duration.minutes(5),
  vpc,
});

// Target group with application-based stickiness
const tg2 = new elbv2.ApplicationTargetGroup(this, 'TG2', {
  targetType: elbv2.TargetType.INSTANCE,
  port: 80,
  stickinessCookieDuration: Duration.minutes(5),
  stickinessCookieName: 'MyDeliciousCookie',
  vpc,
});
python
# vpc: ec2.Vpc


# Target group with duration-based stickiness with load-balancer generated cookie
tg1 = elbv2.ApplicationTargetGroup(self, "TG1",
    target_type=elbv2.TargetType.INSTANCE,
    port=80,
    stickiness_cookie_duration=Duration.minutes(5),
    vpc=vpc
)

# Target group with application-based stickiness
tg2 = elbv2.ApplicationTargetGroup(self, "TG2",
    target_type=elbv2.TargetType.INSTANCE,
    port=80,
    stickiness_cookie_duration=Duration.minutes(5),
    stickiness_cookie_name="MyDeliciousCookie",
    vpc=vpc
)
java
Vpc vpc;


// Target group with duration-based stickiness with load-balancer generated cookie
ApplicationTargetGroup tg1 = ApplicationTargetGroup.Builder.create(this, "TG1")
        .targetType(TargetType.INSTANCE)
        .port(80)
        .stickinessCookieDuration(Duration.minutes(5))
        .vpc(vpc)
        .build();

// Target group with application-based stickiness
ApplicationTargetGroup tg2 = ApplicationTargetGroup.Builder.create(this, "TG2")
        .targetType(TargetType.INSTANCE)
        .port(80)
        .stickinessCookieDuration(Duration.minutes(5))
        .stickinessCookieName("MyDeliciousCookie")
        .vpc(vpc)
        .build();
csharp
Vpc vpc;


// Target group with duration-based stickiness with load-balancer generated cookie
var tg1 = new ApplicationTargetGroup(this, "TG1", new ApplicationTargetGroupProps {
    TargetType = TargetType.INSTANCE,
    Port = 80,
    StickinessCookieDuration = Duration.Minutes(5),
    Vpc = vpc
});

// Target group with application-based stickiness
var tg2 = new ApplicationTargetGroup(this, "TG2", new ApplicationTargetGroupProps {
    TargetType = TargetType.INSTANCE,
    Port = 80,
    StickinessCookieDuration = Duration.Minutes(5),
    StickinessCookieName = "MyDeliciousCookie",
    Vpc = vpc
});
go
var vpc Vpc


// Target group with duration-based stickiness with load-balancer generated cookie
tg1 := elbv2.NewApplicationTargetGroup(this, jsii.String("TG1"), &ApplicationTargetGroupProps{
	TargetType: elbv2.TargetType_INSTANCE,
	Port: jsii.Number(80),
	StickinessCookieDuration: awscdk.Duration_Minutes(jsii.Number(5)),
	Vpc: Vpc,
})

// Target group with application-based stickiness
tg2 := elbv2.NewApplicationTargetGroup(this, jsii.String("TG2"), &ApplicationTargetGroupProps{
	TargetType: elbv2.TargetType_INSTANCE,
	Port: jsii.Number(80),
	StickinessCookieDuration: awscdk.Duration_*Minutes(jsii.Number(5)),
	StickinessCookieName: jsii.String("MyDeliciousCookie"),
	Vpc: Vpc,
})

Slow start mode for your Application Load Balancer ​

By default, a target starts to receive its full share of requests as soon as it is registered with a target group and passes an initial health check. Using slow start mode gives targets time to warm up before the load balancer sends them a full share of requests.

After you enable slow start for a target group, its targets enter slow start mode when they are considered healthy by the target group. A target in slow start mode exits slow start mode when the configured slow start duration period elapses or the target becomes unhealthy. The load balancer linearly increases the number of requests that it can send to a target in slow start mode. After a healthy target exits slow start mode, the load balancer can send it a full share of requests.

The allowed range is 30-900 seconds (15 minutes). The default is 0 seconds (disabled).

ts
declare const vpc: ec2.Vpc;

// Target group with slow start mode enabled
const tg = new elbv2.ApplicationTargetGroup(this, 'TG', {
  targetType: elbv2.TargetType.INSTANCE,
  slowStart: Duration.seconds(60),
  port: 80,
  vpc,
});
python
# vpc: ec2.Vpc


# Target group with slow start mode enabled
tg = elbv2.ApplicationTargetGroup(self, "TG",
    target_type=elbv2.TargetType.INSTANCE,
    slow_start=Duration.seconds(60),
    port=80,
    vpc=vpc
)
java
Vpc vpc;


// Target group with slow start mode enabled
ApplicationTargetGroup tg = ApplicationTargetGroup.Builder.create(this, "TG")
        .targetType(TargetType.INSTANCE)
        .slowStart(Duration.seconds(60))
        .port(80)
        .vpc(vpc)
        .build();
csharp
Vpc vpc;


// Target group with slow start mode enabled
var tg = new ApplicationTargetGroup(this, "TG", new ApplicationTargetGroupProps {
    TargetType = TargetType.INSTANCE,
    SlowStart = Duration.Seconds(60),
    Port = 80,
    Vpc = vpc
});
go
var vpc Vpc


// Target group with slow start mode enabled
tg := elbv2.NewApplicationTargetGroup(this, jsii.String("TG"), &ApplicationTargetGroupProps{
	TargetType: elbv2.TargetType_INSTANCE,
	SlowStart: awscdk.Duration_Seconds(jsii.Number(60)),
	Port: jsii.Number(80),
	Vpc: Vpc,
})

For more information see: <https://docs.aws.amazon.com/elasticloadbalancing/latest/application/sticky-sessions.html#application-based-stickiness>

Setting the target group protocol version ​

By default, Application Load Balancers send requests to targets using HTTP/1.1. You can use the protocol version to send requests to targets using HTTP/2 or gRPC.

ts
declare const vpc: ec2.Vpc;

const tg = new elbv2.ApplicationTargetGroup(this, 'TG', {
  targetType: elbv2.TargetType.IP,
  port: 50051,
  protocol: elbv2.ApplicationProtocol.HTTP,
  protocolVersion: elbv2.ApplicationProtocolVersion.GRPC,
  healthCheck: {
    enabled: true,
    healthyGrpcCodes: '0-99',
  },
  vpc,
});
python
# vpc: ec2.Vpc


tg = elbv2.ApplicationTargetGroup(self, "TG",
    target_type=elbv2.TargetType.IP,
    port=50051,
    protocol=elbv2.ApplicationProtocol.HTTP,
    protocol_version=elbv2.ApplicationProtocolVersion.GRPC,
    health_check=elbv2.HealthCheck(
        enabled=True,
        healthy_grpc_codes="0-99"
    ),
    vpc=vpc
)
java
Vpc vpc;


ApplicationTargetGroup tg = ApplicationTargetGroup.Builder.create(this, "TG")
        .targetType(TargetType.IP)
        .port(50051)
        .protocol(ApplicationProtocol.HTTP)
        .protocolVersion(ApplicationProtocolVersion.GRPC)
        .healthCheck(HealthCheck.builder()
                .enabled(true)
                .healthyGrpcCodes("0-99")
                .build())
        .vpc(vpc)
        .build();
csharp
Vpc vpc;


var tg = new ApplicationTargetGroup(this, "TG", new ApplicationTargetGroupProps {
    TargetType = TargetType.IP,
    Port = 50051,
    Protocol = ApplicationProtocol.HTTP,
    ProtocolVersion = ApplicationProtocolVersion.GRPC,
    HealthCheck = new HealthCheck {
        Enabled = true,
        HealthyGrpcCodes = "0-99"
    },
    Vpc = vpc
});
go
var vpc Vpc


tg := elbv2.NewApplicationTargetGroup(this, jsii.String("TG"), &ApplicationTargetGroupProps{
	TargetType: elbv2.TargetType_IP,
	Port: jsii.Number(50051),
	Protocol: elbv2.ApplicationProtocol_HTTP,
	ProtocolVersion: elbv2.ApplicationProtocolVersion_GRPC,
	HealthCheck: &HealthCheck{
		Enabled: jsii.Boolean(true),
		HealthyGrpcCodes: jsii.String("0-99"),
	},
	Vpc: Vpc,
})

Weighted random routing algorithms and automatic target weights for your Application Load Balancer ​

You can use the weighted_random routing algorithms by setting the loadBalancingAlgorithmType property.

When using this algorithm, Automatic Target Weights (ATW) anomaly mitigation can be used by setting enableAnomalyMitigation to true.

Also you can't use this algorithm with slow start mode.

For more information, see Routing algorithms and Automatic Target Weights (ATW).

ts
declare const vpc: ec2.Vpc;

const tg = new elbv2.ApplicationTargetGroup(this, 'TargetGroup', {
  vpc,
  loadBalancingAlgorithmType: elbv2.TargetGroupLoadBalancingAlgorithmType.WEIGHTED_RANDOM,
  enableAnomalyMitigation: true,
});
python
# vpc: ec2.Vpc


tg = elbv2.ApplicationTargetGroup(self, "TargetGroup",
    vpc=vpc,
    load_balancing_algorithm_type=elbv2.TargetGroupLoadBalancingAlgorithmType.WEIGHTED_RANDOM,
    enable_anomaly_mitigation=True
)
java
Vpc vpc;


ApplicationTargetGroup tg = ApplicationTargetGroup.Builder.create(this, "TargetGroup")
        .vpc(vpc)
        .loadBalancingAlgorithmType(TargetGroupLoadBalancingAlgorithmType.WEIGHTED_RANDOM)
        .enableAnomalyMitigation(true)
        .build();
csharp
Vpc vpc;


var tg = new ApplicationTargetGroup(this, "TargetGroup", new ApplicationTargetGroupProps {
    Vpc = vpc,
    LoadBalancingAlgorithmType = TargetGroupLoadBalancingAlgorithmType.WEIGHTED_RANDOM,
    EnableAnomalyMitigation = true
});
go
var vpc Vpc


tg := elbv2.NewApplicationTargetGroup(this, jsii.String("TargetGroup"), &ApplicationTargetGroupProps{
	Vpc: Vpc,
	LoadBalancingAlgorithmType: elbv2.TargetGroupLoadBalancingAlgorithmType_WEIGHTED_RANDOM,
	EnableAnomalyMitigation: jsii.Boolean(true),
})

Target Group level cross-zone load balancing setting for Application Load Balancers and Network Load Balancers ​

You can set cross-zone load balancing setting at the target group level by setting crossZone property.

If not specified, it will use the load balancer's configuration.

For more information, see How Elastic Load Balancing works.

ts
declare const vpc: ec2.Vpc;

const targetGroup = new elbv2.ApplicationTargetGroup(this, 'TargetGroup', {
  vpc,
  port: 80,
  targetType: elbv2.TargetType.INSTANCE,

  // Whether cross zone load balancing is enabled.
  crossZoneEnabled: true,
});
python
# vpc: ec2.Vpc


target_group = elbv2.ApplicationTargetGroup(self, "TargetGroup",
    vpc=vpc,
    port=80,
    target_type=elbv2.TargetType.INSTANCE,

    # Whether cross zone load balancing is enabled.
    cross_zone_enabled=True
)
java
Vpc vpc;


ApplicationTargetGroup targetGroup = ApplicationTargetGroup.Builder.create(this, "TargetGroup")
        .vpc(vpc)
        .port(80)
        .targetType(TargetType.INSTANCE)

        // Whether cross zone load balancing is enabled.
        .crossZoneEnabled(true)
        .build();
csharp
Vpc vpc;


var targetGroup = new ApplicationTargetGroup(this, "TargetGroup", new ApplicationTargetGroupProps {
    Vpc = vpc,
    Port = 80,
    TargetType = TargetType.INSTANCE,

    // Whether cross zone load balancing is enabled.
    CrossZoneEnabled = true
});
go
var vpc Vpc


targetGroup := elbv2.NewApplicationTargetGroup(this, jsii.String("TargetGroup"), &ApplicationTargetGroupProps{
	Vpc: Vpc,
	Port: jsii.Number(80),
	TargetType: elbv2.TargetType_INSTANCE,

	// Whether cross zone load balancing is enabled.
	CrossZoneEnabled: jsii.Boolean(true),
})

IP Address Type for Target Groups ​

You can set the IP address type for the target group by setting the ipAddressType property for both Application and Network target groups.

If you set the ipAddressType property to IPV6, the VPC for the target group must have an associated IPv6 CIDR block.

For more information, see IP address type for Network Load Balancers and Application Load Balancers.

ts
declare const vpc: ec2.Vpc;

const ipv4ApplicationTargetGroup = new elbv2.ApplicationTargetGroup(this, 'IPv4ApplicationTargetGroup', {
  vpc,
  port: 80,
  targetType: elbv2.TargetType.INSTANCE,
  ipAddressType: elbv2.TargetGroupIpAddressType.IPV4,
});

const ipv6ApplicationTargetGroup = new elbv2.ApplicationTargetGroup(this, 'Ipv6ApplicationTargetGroup', {
  vpc,
  port: 80,
  targetType: elbv2.TargetType.INSTANCE,
  ipAddressType: elbv2.TargetGroupIpAddressType.IPV6,
});

const ipv4NetworkTargetGroup = new elbv2.NetworkTargetGroup(this, 'IPv4NetworkTargetGroup', {
  vpc,
  port: 80,
  targetType: elbv2.TargetType.INSTANCE,
  ipAddressType: elbv2.TargetGroupIpAddressType.IPV4,
});

const ipv6NetworkTargetGroup = new elbv2.NetworkTargetGroup(this, 'Ipv6NetworkTargetGroup', {
  vpc,
  port: 80,
  targetType: elbv2.TargetType.INSTANCE,
  ipAddressType: elbv2.TargetGroupIpAddressType.IPV6,
});
python
# vpc: ec2.Vpc


ipv4_application_target_group = elbv2.ApplicationTargetGroup(self, "IPv4ApplicationTargetGroup",
    vpc=vpc,
    port=80,
    target_type=elbv2.TargetType.INSTANCE,
    ip_address_type=elbv2.TargetGroupIpAddressType.IPV4
)

ipv6_application_target_group = elbv2.ApplicationTargetGroup(self, "Ipv6ApplicationTargetGroup",
    vpc=vpc,
    port=80,
    target_type=elbv2.TargetType.INSTANCE,
    ip_address_type=elbv2.TargetGroupIpAddressType.IPV6
)

ipv4_network_target_group = elbv2.NetworkTargetGroup(self, "IPv4NetworkTargetGroup",
    vpc=vpc,
    port=80,
    target_type=elbv2.TargetType.INSTANCE,
    ip_address_type=elbv2.TargetGroupIpAddressType.IPV4
)

ipv6_network_target_group = elbv2.NetworkTargetGroup(self, "Ipv6NetworkTargetGroup",
    vpc=vpc,
    port=80,
    target_type=elbv2.TargetType.INSTANCE,
    ip_address_type=elbv2.TargetGroupIpAddressType.IPV6
)
java
Vpc vpc;


ApplicationTargetGroup ipv4ApplicationTargetGroup = ApplicationTargetGroup.Builder.create(this, "IPv4ApplicationTargetGroup")
        .vpc(vpc)
        .port(80)
        .targetType(TargetType.INSTANCE)
        .ipAddressType(TargetGroupIpAddressType.IPV4)
        .build();

ApplicationTargetGroup ipv6ApplicationTargetGroup = ApplicationTargetGroup.Builder.create(this, "Ipv6ApplicationTargetGroup")
        .vpc(vpc)
        .port(80)
        .targetType(TargetType.INSTANCE)
        .ipAddressType(TargetGroupIpAddressType.IPV6)
        .build();

NetworkTargetGroup ipv4NetworkTargetGroup = NetworkTargetGroup.Builder.create(this, "IPv4NetworkTargetGroup")
        .vpc(vpc)
        .port(80)
        .targetType(TargetType.INSTANCE)
        .ipAddressType(TargetGroupIpAddressType.IPV4)
        .build();

NetworkTargetGroup ipv6NetworkTargetGroup = NetworkTargetGroup.Builder.create(this, "Ipv6NetworkTargetGroup")
        .vpc(vpc)
        .port(80)
        .targetType(TargetType.INSTANCE)
        .ipAddressType(TargetGroupIpAddressType.IPV6)
        .build();
csharp
Vpc vpc;


var ipv4ApplicationTargetGroup = new ApplicationTargetGroup(this, "IPv4ApplicationTargetGroup", new ApplicationTargetGroupProps {
    Vpc = vpc,
    Port = 80,
    TargetType = TargetType.INSTANCE,
    IpAddressType = TargetGroupIpAddressType.IPV4
});

var ipv6ApplicationTargetGroup = new ApplicationTargetGroup(this, "Ipv6ApplicationTargetGroup", new ApplicationTargetGroupProps {
    Vpc = vpc,
    Port = 80,
    TargetType = TargetType.INSTANCE,
    IpAddressType = TargetGroupIpAddressType.IPV6
});

var ipv4NetworkTargetGroup = new NetworkTargetGroup(this, "IPv4NetworkTargetGroup", new NetworkTargetGroupProps {
    Vpc = vpc,
    Port = 80,
    TargetType = TargetType.INSTANCE,
    IpAddressType = TargetGroupIpAddressType.IPV4
});

var ipv6NetworkTargetGroup = new NetworkTargetGroup(this, "Ipv6NetworkTargetGroup", new NetworkTargetGroupProps {
    Vpc = vpc,
    Port = 80,
    TargetType = TargetType.INSTANCE,
    IpAddressType = TargetGroupIpAddressType.IPV6
});
go
var vpc Vpc


ipv4ApplicationTargetGroup := elbv2.NewApplicationTargetGroup(this, jsii.String("IPv4ApplicationTargetGroup"), &ApplicationTargetGroupProps{
	Vpc: Vpc,
	Port: jsii.Number(80),
	TargetType: elbv2.TargetType_INSTANCE,
	IpAddressType: elbv2.TargetGroupIpAddressType_IPV4,
})

ipv6ApplicationTargetGroup := elbv2.NewApplicationTargetGroup(this, jsii.String("Ipv6ApplicationTargetGroup"), &ApplicationTargetGroupProps{
	Vpc: Vpc,
	Port: jsii.Number(80),
	TargetType: elbv2.TargetType_INSTANCE,
	IpAddressType: elbv2.TargetGroupIpAddressType_IPV6,
})

ipv4NetworkTargetGroup := elbv2.NewNetworkTargetGroup(this, jsii.String("IPv4NetworkTargetGroup"), &NetworkTargetGroupProps{
	Vpc: Vpc,
	Port: jsii.Number(80),
	TargetType: elbv2.TargetType_INSTANCE,
	IpAddressType: elbv2.TargetGroupIpAddressType_IPV4,
})

ipv6NetworkTargetGroup := elbv2.NewNetworkTargetGroup(this, jsii.String("Ipv6NetworkTargetGroup"), &NetworkTargetGroupProps{
	Vpc: Vpc,
	Port: jsii.Number(80),
	TargetType: elbv2.TargetType_INSTANCE,
	IpAddressType: elbv2.TargetGroupIpAddressType_IPV6,
})

Target Group level health setting for Application Load Balancers and Network Load Balancers ​

You can set target group health setting at target group level by setting targetGroupHealth property.

For more information, see How Elastic Load Balancing works.

ts
declare const vpc: ec2.Vpc;

const targetGroup = new elbv2.ApplicationTargetGroup(this, 'TargetGroup', {
  vpc,
  port: 80,
  targetGroupHealth: {
    dnsMinimumHealthyTargetCount: 3,
    dnsMinimumHealthyTargetPercentage: 70,
    routingMinimumHealthyTargetCount: 2,
    routingMinimumHealthyTargetPercentage: 50,
  },
});
python
# vpc: ec2.Vpc


target_group = elbv2.ApplicationTargetGroup(self, "TargetGroup",
    vpc=vpc,
    port=80,
    target_group_health=elbv2.TargetGroupHealth(
        dns_minimum_healthy_target_count=3,
        dns_minimum_healthy_target_percentage=70,
        routing_minimum_healthy_target_count=2,
        routing_minimum_healthy_target_percentage=50
    )
)
java
Vpc vpc;


ApplicationTargetGroup targetGroup = ApplicationTargetGroup.Builder.create(this, "TargetGroup")
        .vpc(vpc)
        .port(80)
        .targetGroupHealth(TargetGroupHealth.builder()
                .dnsMinimumHealthyTargetCount(3)
                .dnsMinimumHealthyTargetPercentage(70)
                .routingMinimumHealthyTargetCount(2)
                .routingMinimumHealthyTargetPercentage(50)
                .build())
        .build();
csharp
Vpc vpc;


var targetGroup = new ApplicationTargetGroup(this, "TargetGroup", new ApplicationTargetGroupProps {
    Vpc = vpc,
    Port = 80,
    TargetGroupHealth = new TargetGroupHealth {
        DnsMinimumHealthyTargetCount = 3,
        DnsMinimumHealthyTargetPercentage = 70,
        RoutingMinimumHealthyTargetCount = 2,
        RoutingMinimumHealthyTargetPercentage = 50
    }
});
go
var vpc Vpc


targetGroup := elbv2.NewApplicationTargetGroup(this, jsii.String("TargetGroup"), &ApplicationTargetGroupProps{
	Vpc: Vpc,
	Port: jsii.Number(80),
	TargetGroupHealth: &TargetGroupHealth{
		DnsMinimumHealthyTargetCount: jsii.Number(3),
		DnsMinimumHealthyTargetPercentage: jsii.Number(70),
		RoutingMinimumHealthyTargetCount: jsii.Number(2),
		RoutingMinimumHealthyTargetPercentage: jsii.Number(50),
	},
})

Using Lambda Targets ​

To use a Lambda Function as a target, use the integration class in the aws-cdk-lib/aws-elasticloadbalancingv2-targets package:

ts
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as targets from 'aws-cdk-lib/aws-elasticloadbalancingv2-targets';

declare const lambdaFunction: lambda.Function;
declare const lb: elbv2.ApplicationLoadBalancer;

const listener = lb.addListener('Listener', { port: 80 });
listener.addTargets('Targets', {
  targets: [new targets.LambdaTarget(lambdaFunction)],

  // For Lambda Targets, you need to explicitly enable health checks if you
  // want them.
  healthCheck: {
    enabled: true,
  }
});
python
import aws_cdk.aws_lambda as lambda_
import aws_cdk.aws_elasticloadbalancingv2_targets as targets

# lambda_function: lambda.Function
# lb: elbv2.ApplicationLoadBalancer


listener = lb.add_listener("Listener", port=80)
listener.add_targets("Targets",
    targets=[targets.LambdaTarget(lambda_function)],

    # For Lambda Targets, you need to explicitly enable health checks if you
    # want them.
    health_check=elbv2.HealthCheck(
        enabled=True
    )
)
java
import software.amazon.awscdk.services.lambda.*;
import software.amazon.awscdk.services.elasticloadbalancingv2.targets.*;

Function lambdaFunction;
ApplicationLoadBalancer lb;


ApplicationListener listener = lb.addListener("Listener", BaseApplicationListenerProps.builder().port(80).build());
listener.addTargets("Targets", AddApplicationTargetsProps.builder()
        .targets(List.of(new LambdaTarget(lambdaFunction)))

        // For Lambda Targets, you need to explicitly enable health checks if you
        // want them.
        .healthCheck(HealthCheck.builder()
                .enabled(true)
                .build())
        .build());
csharp
using Amazon.CDK.AWS.Lambda;
using Amazon.CDK.AWS.ElasticLoadBalancingV2.Targets;

Function lambdaFunction;
ApplicationLoadBalancer lb;


var listener = lb.AddListener("Listener", new BaseApplicationListenerProps { Port = 80 });
listener.AddTargets("Targets", new AddApplicationTargetsProps {
    Targets = new [] { new LambdaTarget(lambdaFunction) },

    // For Lambda Targets, you need to explicitly enable health checks if you
    // want them.
    HealthCheck = new HealthCheck {
        Enabled = true
    }
});
go
import lambda "github.com/aws/aws-cdk-go/awscdk"
import targets "github.com/aws/aws-cdk-go/awscdk"

var lambdaFunction Function
var lb ApplicationLoadBalancer


listener := lb.AddListener(jsii.String("Listener"), &BaseApplicationListenerProps{
	Port: jsii.Number(80),
})
listener.AddTargets(jsii.String("Targets"), &AddApplicationTargetsProps{
	Targets: []IApplicationLoadBalancerTarget{
		targets.NewLambdaTarget(lambdaFunction),
	},

	// For Lambda Targets, you need to explicitly enable health checks if you
	// want them.
	HealthCheck: &HealthCheck{
		Enabled: jsii.Boolean(true),
	},
})

Only a single Lambda function can be added to a single listener rule.

Multi-Value Headers with Lambda Targets ​

When using a Lambda function as a target, you can enable multi-value headers to allow the load balancer to send headers with multiple values:

ts
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as targets from 'aws-cdk-lib/aws-elasticloadbalancingv2-targets';

declare const vpc: ec2.Vpc;
declare const lambdaFunction: lambda.Function;

// Create a target group with multi-value headers enabled
const targetGroup = new elbv2.ApplicationTargetGroup(this, 'LambdaTargetGroup', {
  vpc,
  targets: [new targets.LambdaTarget(lambdaFunction)],

  // Enable multi-value headers
  targetType: elbv2.TargetType.LAMBDA,
  multiValueHeadersEnabled: true,
});
python
import aws_cdk.aws_lambda as lambda_
import aws_cdk.aws_elasticloadbalancingv2_targets as targets

# vpc: ec2.Vpc
# lambda_function: lambda.Function


# Create a target group with multi-value headers enabled
target_group = elbv2.ApplicationTargetGroup(self, "LambdaTargetGroup",
    vpc=vpc,
    targets=[targets.LambdaTarget(lambda_function)],

    # Enable multi-value headers
    target_type=elbv2.TargetType.LAMBDA,
    multi_value_headers_enabled=True
)
java
import software.amazon.awscdk.services.lambda.*;
import software.amazon.awscdk.services.elasticloadbalancingv2.targets.*;

Vpc vpc;
Function lambdaFunction;


// Create a target group with multi-value headers enabled
ApplicationTargetGroup targetGroup = ApplicationTargetGroup.Builder.create(this, "LambdaTargetGroup")
        .vpc(vpc)
        .targets(List.of(new LambdaTarget(lambdaFunction)))

        // Enable multi-value headers
        .targetType(TargetType.LAMBDA)
        .multiValueHeadersEnabled(true)
        .build();
csharp
using Amazon.CDK.AWS.Lambda;
using Amazon.CDK.AWS.ElasticLoadBalancingV2.Targets;

Vpc vpc;
Function lambdaFunction;


// Create a target group with multi-value headers enabled
var targetGroup = new ApplicationTargetGroup(this, "LambdaTargetGroup", new ApplicationTargetGroupProps {
    Vpc = vpc,
    Targets = new [] { new LambdaTarget(lambdaFunction) },

    // Enable multi-value headers
    TargetType = TargetType.LAMBDA,
    MultiValueHeadersEnabled = true
});
go
import lambda "github.com/aws/aws-cdk-go/awscdk"
import targets "github.com/aws/aws-cdk-go/awscdk"

var vpc Vpc
var lambdaFunction Function


// Create a target group with multi-value headers enabled
targetGroup := elbv2.NewApplicationTargetGroup(this, jsii.String("LambdaTargetGroup"), &ApplicationTargetGroupProps{
	Vpc: Vpc,
	Targets: []IApplicationLoadBalancerTarget{
		targets.NewLambdaTarget(lambdaFunction),
	},

	// Enable multi-value headers
	TargetType: elbv2.TargetType_LAMBDA,
	MultiValueHeadersEnabled: jsii.Boolean(true),
})

When multi-value headers are enabled, the request and response headers exchanged between the load balancer and the Lambda function include headers with multiple values. If this option is disabled (the default) and the request contains a duplicate header field name, the load balancer uses the last value sent by the client.

Using Application Load Balancer Targets ​

To use a single application load balancer as a target for the network load balancer, use the integration class in the aws-cdk-lib/aws-elasticloadbalancingv2-targets package:

ts
import * as targets from 'aws-cdk-lib/aws-elasticloadbalancingv2-targets';
import * as ecs from 'aws-cdk-lib/aws-ecs';
import * as patterns from 'aws-cdk-lib/aws-ecs-patterns';

declare const vpc: ec2.Vpc;

const task = new ecs.FargateTaskDefinition(this, 'Task', { cpu: 256, memoryLimitMiB: 512 });
task.addContainer('nginx', {
  image: ecs.ContainerImage.fromRegistry('public.ecr.aws/nginx/nginx:latest'),
  portMappings: [{ containerPort: 80 }],
});

const svc = new patterns.ApplicationLoadBalancedFargateService(this, 'Service', {
  vpc,
  taskDefinition: task,
  publicLoadBalancer: false,
});

const nlb = new elbv2.NetworkLoadBalancer(this, 'Nlb', {
  vpc,
  crossZoneEnabled: true,
  internetFacing: true,
});

const listener = nlb.addListener('listener', { port: 80 });

listener.addTargets('Targets', {
  targets: [new targets.AlbListenerTarget(svc.listener)],
  port: 80,
});

new CfnOutput(this, 'NlbEndpoint', { value: `http://${nlb.loadBalancerDnsName}`})
python
import aws_cdk.aws_elasticloadbalancingv2_targets as targets
import aws_cdk.aws_ecs as ecs
import aws_cdk.aws_ecs_patterns as patterns

# vpc: ec2.Vpc


task = ecs.FargateTaskDefinition(self, "Task", cpu=256, memory_limit_mi_b=512)
task.add_container("nginx",
    image=ecs.ContainerImage.from_registry("public.ecr.aws/nginx/nginx:latest"),
    port_mappings=[ecs.PortMapping(container_port=80)]
)

svc = patterns.ApplicationLoadBalancedFargateService(self, "Service",
    vpc=vpc,
    task_definition=task,
    public_load_balancer=False
)

nlb = elbv2.NetworkLoadBalancer(self, "Nlb",
    vpc=vpc,
    cross_zone_enabled=True,
    internet_facing=True
)

listener = nlb.add_listener("listener", port=80)

listener.add_targets("Targets",
    targets=[targets.AlbListenerTarget(svc.listener)],
    port=80
)

CfnOutput(self, "NlbEndpoint", value=f"http://{nlb.loadBalancerDnsName}")
java
import software.amazon.awscdk.services.elasticloadbalancingv2.targets.*;
import software.amazon.awscdk.services.ecs.*;
import software.amazon.awscdk.services.ecs.patterns.*;

Vpc vpc;


FargateTaskDefinition task = FargateTaskDefinition.Builder.create(this, "Task").cpu(256).memoryLimitMiB(512).build();
task.addContainer("nginx", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("public.ecr.aws/nginx/nginx:latest"))
        .portMappings(List.of(PortMapping.builder().containerPort(80).build()))
        .build());

ApplicationLoadBalancedFargateService svc = ApplicationLoadBalancedFargateService.Builder.create(this, "Service")
        .vpc(vpc)
        .taskDefinition(task)
        .publicLoadBalancer(false)
        .build();

NetworkLoadBalancer nlb = NetworkLoadBalancer.Builder.create(this, "Nlb")
        .vpc(vpc)
        .crossZoneEnabled(true)
        .internetFacing(true)
        .build();

NetworkListener listener = nlb.addListener("listener", BaseNetworkListenerProps.builder().port(80).build());

listener.addTargets("Targets", AddNetworkTargetsProps.builder()
        .targets(List.of(new AlbListenerTarget(svc.getListener())))
        .port(80)
        .build());

CfnOutput.Builder.create(this, "NlbEndpoint").value(String.format("http://%s", nlb.getLoadBalancerDnsName())).build();
csharp
using Amazon.CDK.AWS.ElasticLoadBalancingV2.Targets;
using Amazon.CDK.AWS.ECS;
using Amazon.CDK.AWS.ECS.Patterns;

Vpc vpc;


var task = new FargateTaskDefinition(this, "Task", new FargateTaskDefinitionProps { Cpu = 256, MemoryLimitMiB = 512 });
task.AddContainer("nginx", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("public.ecr.aws/nginx/nginx:latest"),
    PortMappings = new [] { new PortMapping { ContainerPort = 80 } }
});

var svc = new ApplicationLoadBalancedFargateService(this, "Service", new ApplicationLoadBalancedFargateServiceProps {
    Vpc = vpc,
    TaskDefinition = task,
    PublicLoadBalancer = false
});

var nlb = new NetworkLoadBalancer(this, "Nlb", new NetworkLoadBalancerProps {
    Vpc = vpc,
    CrossZoneEnabled = true,
    InternetFacing = true
});

var listener = nlb.AddListener("listener", new BaseNetworkListenerProps { Port = 80 });

listener.AddTargets("Targets", new AddNetworkTargetsProps {
    Targets = new [] { new AlbListenerTarget(svc.Listener) },
    Port = 80
});

new CfnOutput(this, "NlbEndpoint", new CfnOutputProps { Value = $"http://{nlb.loadBalancerDnsName}" });
go
import targets "github.com/aws/aws-cdk-go/awscdk"
import "github.com/aws/aws-cdk-go/awscdk"
import patterns "github.com/aws/aws-cdk-go/awscdk"

var vpc Vpc


task := ecs.NewFargateTaskDefinition(this, jsii.String("Task"), &FargateTaskDefinitionProps{
	Cpu: jsii.Number(256),
	MemoryLimitMiB: jsii.Number(512),
})
task.AddContainer(jsii.String("nginx"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("public.ecr.aws/nginx/nginx:latest")),
	PortMappings: []PortMapping{
		&PortMapping{
			ContainerPort: jsii.Number(80),
		},
	},
})

svc := patterns.NewApplicationLoadBalancedFargateService(this, jsii.String("Service"), &ApplicationLoadBalancedFargateServiceProps{
	Vpc: Vpc,
	TaskDefinition: task,
	PublicLoadBalancer: jsii.Boolean(false),
})

nlb := elbv2.NewNetworkLoadBalancer(this, jsii.String("Nlb"), &NetworkLoadBalancerProps{
	Vpc: Vpc,
	CrossZoneEnabled: jsii.Boolean(true),
	InternetFacing: jsii.Boolean(true),
})

listener := nlb.AddListener(jsii.String("listener"), &BaseNetworkListenerProps{
	Port: jsii.Number(80),
})

listener.AddTargets(jsii.String("Targets"), &AddNetworkTargetsProps{
	Targets: []INetworkLoadBalancerTarget{
		targets.NewAlbListenerTarget(svc.Listener),
	},
	Port: jsii.Number(80),
})

awscdk.NewCfnOutput(this, jsii.String("NlbEndpoint"), &CfnOutputProps{
	Value: fmt.Sprintf("http://%v", nlb.LoadBalancerDnsName),
})

Only the network load balancer is allowed to add the application load balancer as the target.

Configuring Health Checks ​

Health checks are configured upon creation of a target group:

ts
declare const listener: elbv2.ApplicationListener;
declare const asg: autoscaling.AutoScalingGroup;

listener.addTargets('AppFleet', {
  port: 8080,
  targets: [asg],
  healthCheck: {
    path: '/ping',
    interval: Duration.minutes(1),
  }
});
python
# listener: elbv2.ApplicationListener
# asg: autoscaling.AutoScalingGroup


listener.add_targets("AppFleet",
    port=8080,
    targets=[asg],
    health_check=elbv2.HealthCheck(
        path="/ping",
        interval=Duration.minutes(1)
    )
)
java
ApplicationListener listener;
AutoScalingGroup asg;


listener.addTargets("AppFleet", AddApplicationTargetsProps.builder()
        .port(8080)
        .targets(List.of(asg))
        .healthCheck(HealthCheck.builder()
                .path("/ping")
                .interval(Duration.minutes(1))
                .build())
        .build());
csharp
ApplicationListener listener;
AutoScalingGroup asg;


listener.AddTargets("AppFleet", new AddApplicationTargetsProps {
    Port = 8080,
    Targets = new [] { asg },
    HealthCheck = new HealthCheck {
        Path = "/ping",
        Interval = Duration.Minutes(1)
    }
});
go
var listener ApplicationListener
var asg AutoScalingGroup


listener.AddTargets(jsii.String("AppFleet"), &AddApplicationTargetsProps{
	Port: jsii.Number(8080),
	Targets: []IApplicationLoadBalancerTarget{
		asg,
	},
	HealthCheck: &HealthCheck{
		Path: jsii.String("/ping"),
		Interval: awscdk.Duration_Minutes(jsii.Number(1)),
	},
})

The health check can also be configured after creation by calling configureHealthCheck() on the created object.

No attempts are made to configure security groups for the port you're configuring a health check for, but if the health check is on the same port you're routing traffic to, the security group already allows the traffic. If not, you will have to configure the security groups appropriately:

ts
declare const lb: elbv2.ApplicationLoadBalancer;
declare const listener: elbv2.ApplicationListener;
declare const asg: autoscaling.AutoScalingGroup;

listener.addTargets('AppFleet', {
  port: 8080,
  targets: [asg],
  healthCheck: {
    port: '8088',
  }
});

asg.connections.allowFrom(lb, ec2.Port.tcp(8088));
python
# lb: elbv2.ApplicationLoadBalancer
# listener: elbv2.ApplicationListener
# asg: autoscaling.AutoScalingGroup


listener.add_targets("AppFleet",
    port=8080,
    targets=[asg],
    health_check=elbv2.HealthCheck(
        port="8088"
    )
)

asg.connections.allow_from(lb, ec2.Port.tcp(8088))
java
ApplicationLoadBalancer lb;
ApplicationListener listener;
AutoScalingGroup asg;


listener.addTargets("AppFleet", AddApplicationTargetsProps.builder()
        .port(8080)
        .targets(List.of(asg))
        .healthCheck(HealthCheck.builder()
                .port("8088")
                .build())
        .build());

asg.connections.allowFrom(lb, Port.tcp(8088));
csharp
ApplicationLoadBalancer lb;
ApplicationListener listener;
AutoScalingGroup asg;


listener.AddTargets("AppFleet", new AddApplicationTargetsProps {
    Port = 8080,
    Targets = new [] { asg },
    HealthCheck = new HealthCheck {
        Port = "8088"
    }
});

asg.Connections.AllowFrom(lb, Port.Tcp(8088));
go
var lb ApplicationLoadBalancer
var listener ApplicationListener
var asg AutoScalingGroup


listener.AddTargets(jsii.String("AppFleet"), &AddApplicationTargetsProps{
	Port: jsii.Number(8080),
	Targets: []IApplicationLoadBalancerTarget{
		asg,
	},
	HealthCheck: &HealthCheck{
		Port: jsii.String("8088"),
	},
})

asg.connections.AllowFrom(lb, ec2.Port_Tcp(jsii.Number(8088)))

Using a Load Balancer from a different Stack ​

If you want to put your Load Balancer and the Targets it is load balancing to in different stacks, you may not be able to use the convenience methods loadBalancer.addListener() and listener.addTargets().

The reason is that these methods will create resources in the same Stack as the object they're called on, which may lead to cyclic references between stacks. Instead, you will have to create an ApplicationListener in the target stack, or an empty TargetGroup in the load balancer stack that you attach your service to.

For an example of the alternatives while load balancing to an ECS service, see the ecs/cross-stack-load-balancer example.

Protocol for Load Balancer Targets ​

Constructs that want to be a load balancer target should implement IApplicationLoadBalancerTarget and/or INetworkLoadBalancerTarget, and provide an implementation for the function attachToXxxTargetGroup(), which can call functions on the load balancer and should return metadata about the load balancing target:

ts
class MyTarget implements elbv2.IApplicationLoadBalancerTarget {
  public attachToApplicationTargetGroup(targetGroup: elbv2.ApplicationTargetGroup): elbv2.LoadBalancerTargetProps {
    // If we need to add security group rules
    // targetGroup.registerConnectable(...);
    return {
      targetType: elbv2.TargetType.IP,
      targetJson: { id: '1.2.3.4', port: 8080 },
    };
  }
}
python
@jsii.implements(elbv2.IApplicationLoadBalancerTarget)
class MyTarget:
    def attach_to_application_target_group(self, target_group):
        # If we need to add security group rules
        # targetGroup.registerConnectable(...);
        return elbv2.LoadBalancerTargetProps(
            target_type=elbv2.TargetType.IP,
            target_json={"id": "1.2.3.4", "port": 8080}
        )
java
public class MyTarget implements IApplicationLoadBalancerTarget {
    public LoadBalancerTargetProps attachToApplicationTargetGroup(ApplicationTargetGroup targetGroup) {
        // If we need to add security group rules
        // targetGroup.registerConnectable(...);
        return LoadBalancerTargetProps.builder()
                .targetType(TargetType.IP)
                .targetJson(Map.of("id", "1.2.3.4", "port", 8080))
                .build();
    }
}
csharp
class MyTarget : IApplicationLoadBalancerTarget
{
    public LoadBalancerTargetProps AttachToApplicationTargetGroup(ApplicationTargetGroup targetGroup)
    {
        // If we need to add security group rules
        // targetGroup.registerConnectable(...);
        return new LoadBalancerTargetProps {
            TargetType = TargetType.IP,
            TargetJson = new Struct { Id = "1.2.3.4", Port = 8080 }
        };
    }
}
go
type myTarget struct {
}

func (this *myTarget) attachToApplicationTargetGroup(targetGroup ApplicationTargetGroup) LoadBalancerTargetProps {
	// If we need to add security group rules
	// targetGroup.registerConnectable(...);
	return &LoadBalancerTargetProps{
		TargetType: elbv2.TargetType_IP,
		TargetJson: map[string]interface{}{
			"id": jsii.String("1.2.3.4"),
			"port": jsii.Number(8080),
		},
	}
}

targetType should be one of Instance or Ip. If the target can be directly added to the target group, targetJson should contain the id of the target (either instance ID or IP address depending on the type) and optionally a port or availabilityZone override.

Application load balancer targets can call registerConnectable() on the target group to register themselves for addition to the load balancer's security group rules.

If your load balancer target requires that the TargetGroup has been associated with a LoadBalancer before registration can happen (such as is the case for ECS Services for example), take a resource dependency on targetGroup.loadBalancerAttached as follows:

ts
declare const resource: Resource;
declare const targetGroup: elbv2.ApplicationTargetGroup;

// Make sure that the listener has been created, and so the TargetGroup
// has been associated with the LoadBalancer, before 'resource' is created.

Node.of(resource).addDependency(targetGroup.loadBalancerAttached);
python
# resource: Resource
# target_group: elbv2.ApplicationTargetGroup


# Make sure that the listener has been created, and so the TargetGroup
# has been associated with the LoadBalancer, before 'resource' is created.

Node.of(resource).add_dependency(target_group.load_balancer_attached)
java
Resource resource;
ApplicationTargetGroup targetGroup;


// Make sure that the listener has been created, and so the TargetGroup
// has been associated with the LoadBalancer, before 'resource' is created.

Node.of(resource).addDependency(targetGroup.getLoadBalancerAttached());
csharp
Resource resource;
ApplicationTargetGroup targetGroup;


// Make sure that the listener has been created, and so the TargetGroup
// has been associated with the LoadBalancer, before 'resource' is created.

Node.Of(resource).AddDependency(targetGroup.LoadBalancerAttached);
go
var resource Resource
var targetGroup ApplicationTargetGroup


// Make sure that the listener has been created, and so the TargetGroup
// has been associated with the LoadBalancer, before 'resource' is created.

constructs.Node_Of(resource).AddDependency(targetGroup.loadBalancerAttached)

Looking up Load Balancers and Listeners ​

You may look up load balancers and load balancer listeners by using one of the following lookup methods:

  • ApplicationLoadBalancer.fromLookup(options) - Look up an application load balancer.
  • ApplicationListener.fromLookup(options) - Look up an application load balancer listener.
  • NetworkLoadBalancer.fromLookup(options) - Look up a network load balancer.
  • NetworkListener.fromLookup(options) - Look up a network load balancer listener.

Load Balancer lookup options ​

You may look up a load balancer by ARN or by associated tags. When you look a load balancer up by ARN, that load balancer will be returned unless CDK detects that the load balancer is of the wrong type. When you look up a load balancer by tags, CDK will return the load balancer matching all specified tags. If more than one load balancer matches, CDK will throw an error requesting that you provide more specific criteria.

Look up a Application Load Balancer by ARN

ts
const loadBalancer = elbv2.ApplicationLoadBalancer.fromLookup(this, 'ALB', {
  loadBalancerArn: 'arn:aws:elasticloadbalancing:us-east-2:123456789012:loadbalancer/app/my-load-balancer/1234567890123456',
});
python
load_balancer = elbv2.ApplicationLoadBalancer.from_lookup(self, "ALB",
    load_balancer_arn="arn:aws:elasticloadbalancing:us-east-2:123456789012:loadbalancer/app/my-load-balancer/1234567890123456"
)
java
IApplicationLoadBalancer loadBalancer = ApplicationLoadBalancer.fromLookup(this, "ALB", ApplicationLoadBalancerLookupOptions.builder()
        .loadBalancerArn("arn:aws:elasticloadbalancing:us-east-2:123456789012:loadbalancer/app/my-load-balancer/1234567890123456")
        .build());
csharp
var loadBalancer = ApplicationLoadBalancer.FromLookup(this, "ALB", new ApplicationLoadBalancerLookupOptions {
    LoadBalancerArn = "arn:aws:elasticloadbalancing:us-east-2:123456789012:loadbalancer/app/my-load-balancer/1234567890123456"
});
go
loadBalancer := elbv2.ApplicationLoadBalancer_FromLookup(this, jsii.String("ALB"), &ApplicationLoadBalancerLookupOptions{
	LoadBalancerArn: jsii.String("arn:aws:elasticloadbalancing:us-east-2:123456789012:loadbalancer/app/my-load-balancer/1234567890123456"),
})

Look up an Application Load Balancer by tags

ts
const loadBalancer = elbv2.ApplicationLoadBalancer.fromLookup(this, 'ALB', {
  loadBalancerTags: {
    // Finds a load balancer matching all tags.
    some: 'tag',
    someother: 'tag',
  },
});
python
load_balancer = elbv2.ApplicationLoadBalancer.from_lookup(self, "ALB",
    load_balancer_tags={
        # Finds a load balancer matching all tags.
        "some": "tag",
        "someother": "tag"
    }
)
java
IApplicationLoadBalancer loadBalancer = ApplicationLoadBalancer.fromLookup(this, "ALB", ApplicationLoadBalancerLookupOptions.builder()
        .loadBalancerTags(Map.of(
                // Finds a load balancer matching all tags.
                "some", "tag",
                "someother", "tag"))
        .build());
csharp
var loadBalancer = ApplicationLoadBalancer.FromLookup(this, "ALB", new ApplicationLoadBalancerLookupOptions {
    LoadBalancerTags = new Dictionary<string, string> {
        // Finds a load balancer matching all tags.
        { "some", "tag" },
        { "someother", "tag" }
    }
});
go
loadBalancer := elbv2.ApplicationLoadBalancer_FromLookup(this, jsii.String("ALB"), &ApplicationLoadBalancerLookupOptions{
	LoadBalancerTags: map[string]*string{
		// Finds a load balancer matching all tags.
		"some": jsii.String("tag"),
		"someother": jsii.String("tag"),
	},
})

Load Balancer Listener lookup options ​

You may look up a load balancer listener by the following criteria:

  • Associated load balancer ARN
  • Associated load balancer tags
  • Listener ARN
  • Listener port
  • Listener protocol

The lookup method will return the matching listener. If more than one listener matches, CDK will throw an error requesting that you specify additional criteria.

Look up a Listener by associated Load Balancer, Port, and Protocol

ts
const listener = elbv2.ApplicationListener.fromLookup(this, 'ALBListener', {
  loadBalancerArn: 'arn:aws:elasticloadbalancing:us-east-2:123456789012:loadbalancer/app/my-load-balancer/1234567890123456',
  listenerProtocol: elbv2.ApplicationProtocol.HTTPS,
  listenerPort: 443,
});
python
listener = elbv2.ApplicationListener.from_lookup(self, "ALBListener",
    load_balancer_arn="arn:aws:elasticloadbalancing:us-east-2:123456789012:loadbalancer/app/my-load-balancer/1234567890123456",
    listener_protocol=elbv2.ApplicationProtocol.HTTPS,
    listener_port=443
)
java
IApplicationListener listener = ApplicationListener.fromLookup(this, "ALBListener", ApplicationListenerLookupOptions.builder()
        .loadBalancerArn("arn:aws:elasticloadbalancing:us-east-2:123456789012:loadbalancer/app/my-load-balancer/1234567890123456")
        .listenerProtocol(ApplicationProtocol.HTTPS)
        .listenerPort(443)
        .build());
csharp
var listener = ApplicationListener.FromLookup(this, "ALBListener", new ApplicationListenerLookupOptions {
    LoadBalancerArn = "arn:aws:elasticloadbalancing:us-east-2:123456789012:loadbalancer/app/my-load-balancer/1234567890123456",
    ListenerProtocol = ApplicationProtocol.HTTPS,
    ListenerPort = 443
});
go
listener := elbv2.ApplicationListener_FromLookup(this, jsii.String("ALBListener"), &ApplicationListenerLookupOptions{
	LoadBalancerArn: jsii.String("arn:aws:elasticloadbalancing:us-east-2:123456789012:loadbalancer/app/my-load-balancer/1234567890123456"),
	ListenerProtocol: elbv2.ApplicationProtocol_HTTPS,
	ListenerPort: jsii.Number(443),
})

Look up a Listener by associated Load Balancer Tag, Port, and Protocol

ts
const listener = elbv2.ApplicationListener.fromLookup(this, 'ALBListener', {
  loadBalancerTags: {
    Cluster: 'MyClusterName',
  },
  listenerProtocol: elbv2.ApplicationProtocol.HTTPS,
  listenerPort: 443,
});
python
listener = elbv2.ApplicationListener.from_lookup(self, "ALBListener",
    load_balancer_tags={
        "Cluster": "MyClusterName"
    },
    listener_protocol=elbv2.ApplicationProtocol.HTTPS,
    listener_port=443
)
java
IApplicationListener listener = ApplicationListener.fromLookup(this, "ALBListener", ApplicationListenerLookupOptions.builder()
        .loadBalancerTags(Map.of(
                "Cluster", "MyClusterName"))
        .listenerProtocol(ApplicationProtocol.HTTPS)
        .listenerPort(443)
        .build());
csharp
var listener = ApplicationListener.FromLookup(this, "ALBListener", new ApplicationListenerLookupOptions {
    LoadBalancerTags = new Dictionary<string, string> {
        { "Cluster", "MyClusterName" }
    },
    ListenerProtocol = ApplicationProtocol.HTTPS,
    ListenerPort = 443
});
go
listener := elbv2.ApplicationListener_FromLookup(this, jsii.String("ALBListener"), &ApplicationListenerLookupOptions{
	LoadBalancerTags: map[string]*string{
		"Cluster": jsii.String("MyClusterName"),
	},
	ListenerProtocol: elbv2.ApplicationProtocol_HTTPS,
	ListenerPort: jsii.Number(443),
})

Look up a Network Listener by associated Load Balancer Tag, Port, and Protocol

ts
const listener = elbv2.NetworkListener.fromLookup(this, 'ALBListener', {
  loadBalancerTags: {
    Cluster: 'MyClusterName',
  },
  listenerProtocol: elbv2.Protocol.TCP,
  listenerPort: 12345,
});
python
listener = elbv2.NetworkListener.from_lookup(self, "ALBListener",
    load_balancer_tags={
        "Cluster": "MyClusterName"
    },
    listener_protocol=elbv2.Protocol.TCP,
    listener_port=12345
)
java
INetworkListener listener = NetworkListener.fromLookup(this, "ALBListener", NetworkListenerLookupOptions.builder()
        .loadBalancerTags(Map.of(
                "Cluster", "MyClusterName"))
        .listenerProtocol(Protocol.TCP)
        .listenerPort(12345)
        .build());
csharp
var listener = NetworkListener.FromLookup(this, "ALBListener", new NetworkListenerLookupOptions {
    LoadBalancerTags = new Dictionary<string, string> {
        { "Cluster", "MyClusterName" }
    },
    ListenerProtocol = Protocol.TCP,
    ListenerPort = 12345
});
go
listener := elbv2.NetworkListener_FromLookup(this, jsii.String("ALBListener"), &NetworkListenerLookupOptions{
	LoadBalancerTags: map[string]*string{
		"Cluster": jsii.String("MyClusterName"),
	},
	ListenerProtocol: elbv2.Protocol_TCP,
	ListenerPort: jsii.Number(12345),
})

Metrics ​

You may create metrics for Load Balancers and Target Groups through the metrics attribute:

Load Balancer:

ts
declare const alb: elbv2.IApplicationLoadBalancer;

const albMetrics: elbv2.IApplicationLoadBalancerMetrics = alb.metrics;
const metricConnectionCount: cloudwatch.Metric = albMetrics.activeConnectionCount();
python
# alb: elbv2.IApplicationLoadBalancer


alb_metrics = alb.metrics
metric_connection_count = alb_metrics.active_connection_count()
java
IApplicationLoadBalancer alb;


IApplicationLoadBalancerMetrics albMetrics = alb.getMetrics();
Metric metricConnectionCount = albMetrics.activeConnectionCount();
csharp
IApplicationLoadBalancer alb;


var albMetrics = alb.Metrics;
var metricConnectionCount = albMetrics.ActiveConnectionCount();
go
var alb IApplicationLoadBalancer


albMetrics := alb.Metrics
metricConnectionCount := albMetrics.ActiveConnectionCount()

Target Group:

ts
declare const targetGroup: elbv2.IApplicationTargetGroup;

const targetGroupMetrics: elbv2.IApplicationTargetGroupMetrics = targetGroup.metrics;
const metricHealthyHostCount: cloudwatch.Metric = targetGroupMetrics.healthyHostCount();
python
# target_group: elbv2.IApplicationTargetGroup


target_group_metrics = target_group.metrics
metric_healthy_host_count = target_group_metrics.healthy_host_count()
java
IApplicationTargetGroup targetGroup;


IApplicationTargetGroupMetrics targetGroupMetrics = targetGroup.getMetrics();
Metric metricHealthyHostCount = targetGroupMetrics.healthyHostCount();
csharp
IApplicationTargetGroup targetGroup;


var targetGroupMetrics = targetGroup.Metrics;
var metricHealthyHostCount = targetGroupMetrics.HealthyHostCount();
go
var targetGroup IApplicationTargetGroup


targetGroupMetrics := targetGroup.Metrics
metricHealthyHostCount := targetGroupMetrics.HealthyHostCount()

Metrics are also available to imported resources:

ts
declare const stack: Stack;

const targetGroup = elbv2.ApplicationTargetGroup.fromTargetGroupAttributes(this, 'MyTargetGroup', {
  targetGroupArn: Fn.importValue('TargetGroupArn'),
  loadBalancerArns: Fn.importValue('LoadBalancerArn'),
});

const targetGroupMetrics: elbv2.IApplicationTargetGroupMetrics = targetGroup.metrics;
python
# stack: Stack


target_group = elbv2.ApplicationTargetGroup.from_target_group_attributes(self, "MyTargetGroup",
    target_group_arn=Fn.import_value("TargetGroupArn"),
    load_balancer_arns=Fn.import_value("LoadBalancerArn")
)

target_group_metrics = target_group.metrics
java
Stack stack;


IApplicationTargetGroup targetGroup = ApplicationTargetGroup.fromTargetGroupAttributes(this, "MyTargetGroup", TargetGroupAttributes.builder()
        .targetGroupArn(Fn.importValue("TargetGroupArn"))
        .loadBalancerArns(Fn.importValue("LoadBalancerArn"))
        .build());

IApplicationTargetGroupMetrics targetGroupMetrics = targetGroup.getMetrics();
csharp
Stack stack;


var targetGroup = ApplicationTargetGroup.FromTargetGroupAttributes(this, "MyTargetGroup", new TargetGroupAttributes {
    TargetGroupArn = Fn.ImportValue("TargetGroupArn"),
    LoadBalancerArns = Fn.ImportValue("LoadBalancerArn")
});

var targetGroupMetrics = targetGroup.Metrics;
go
var stack Stack


targetGroup := elbv2.ApplicationTargetGroup_FromTargetGroupAttributes(this, jsii.String("MyTargetGroup"), &TargetGroupAttributes{
	TargetGroupArn: awscdk.Fn_ImportValue(jsii.String("TargetGroupArn")),
	LoadBalancerArns: awscdk.Fn_*ImportValue(jsii.String("LoadBalancerArn")),
})

targetGroupMetrics := targetGroup.Metrics

Notice that TargetGroups must be imported by supplying the Load Balancer too, otherwise accessing the metrics will throw an error:

ts
declare const stack: Stack;
const targetGroup = elbv2.ApplicationTargetGroup.fromTargetGroupAttributes(this, 'MyTargetGroup', {
  targetGroupArn: Fn.importValue('TargetGroupArn'),
});

const targetGroupMetrics: elbv2.IApplicationTargetGroupMetrics = targetGroup.metrics; // throws an Error()
python
# stack: Stack

target_group = elbv2.ApplicationTargetGroup.from_target_group_attributes(self, "MyTargetGroup",
    target_group_arn=Fn.import_value("TargetGroupArn")
)

target_group_metrics = target_group.metrics
java
Stack stack;

IApplicationTargetGroup targetGroup = ApplicationTargetGroup.fromTargetGroupAttributes(this, "MyTargetGroup", TargetGroupAttributes.builder()
        .targetGroupArn(Fn.importValue("TargetGroupArn"))
        .build());

IApplicationTargetGroupMetrics targetGroupMetrics = targetGroup.getMetrics();
csharp
Stack stack;

var targetGroup = ApplicationTargetGroup.FromTargetGroupAttributes(this, "MyTargetGroup", new TargetGroupAttributes {
    TargetGroupArn = Fn.ImportValue("TargetGroupArn")
});

var targetGroupMetrics = targetGroup.Metrics;
go
var stack Stack

targetGroup := elbv2.ApplicationTargetGroup_FromTargetGroupAttributes(this, jsii.String("MyTargetGroup"), &TargetGroupAttributes{
	TargetGroupArn: awscdk.Fn_ImportValue(jsii.String("TargetGroupArn")),
})

targetGroupMetrics := targetGroup.Metrics

logicalIds on ExternalApplicationListener.addTargetGroups() and .addAction() ​

By default, the addTargetGroups() method does not follow the standard behavior of adding a Rule suffix to the logicalId of the ListenerRule it creates. If you are deploying new ListenerRules using addTargetGroups() the recommendation is to set the removeRuleSuffixFromLogicalId: false property. If you have ListenerRules deployed using the legacy behavior of addTargetGroups(), which you need to switch over to being managed by the addAction() method, then you will need to enable the removeRuleSuffixFromLogicalId: true property in the addAction() method.

ListenerRules have a unique priority for a given Listener. Because the priority must be unique, CloudFormation will always fail when creating a new ListenerRule to replace the existing one, unless you change the priority as well as the logicalId.

Configuring Mutual authentication with TLS in Application Load Balancer ​

You can configure Mutual authentication with TLS (mTLS) for Application Load Balancer.

To set mTLS, you must create an instance of TrustStore and set it to ApplicationListener.

For more information, see Mutual authentication with TLS in Application Load Balancer

ts
import * as acm from 'aws-cdk-lib/aws-certificatemanager';

declare const certificate: acm.Certificate;
declare const lb: elbv2.ApplicationLoadBalancer;
declare const bucket: s3.Bucket;

const trustStore = new elbv2.TrustStore(this, 'Store', {
  bucket,
  key: 'rootCA_cert.pem',
});

lb.addListener('Listener', {
  port: 443,
  protocol: elbv2.ApplicationProtocol.HTTPS,
  certificates: [certificate],
  // mTLS settings
  mutualAuthentication: {
    advertiseTrustStoreCaNames: true,
    ignoreClientCertificateExpiry: false,
    mutualAuthenticationMode: elbv2.MutualAuthenticationMode.VERIFY,
    trustStore,
  },
  defaultAction: elbv2.ListenerAction.fixedResponse(200,
    { contentType: 'text/plain', messageBody: 'Success mTLS' }),
});
python
import aws_cdk.aws_certificatemanager as acm

# certificate: acm.Certificate
# lb: elbv2.ApplicationLoadBalancer
# bucket: s3.Bucket


trust_store = elbv2.TrustStore(self, "Store",
    bucket=bucket,
    key="rootCA_cert.pem"
)

lb.add_listener("Listener",
    port=443,
    protocol=elbv2.ApplicationProtocol.HTTPS,
    certificates=[certificate],
    # mTLS settings
    mutual_authentication=elbv2.MutualAuthentication(
        advertise_trust_store_ca_names=True,
        ignore_client_certificate_expiry=False,
        mutual_authentication_mode=elbv2.MutualAuthenticationMode.VERIFY,
        trust_store=trust_store
    ),
    default_action=elbv2.ListenerAction.fixed_response(200, content_type="text/plain", message_body="Success mTLS")
)
java
import software.amazon.awscdk.services.certificatemanager.*;

Certificate certificate;
ApplicationLoadBalancer lb;
Bucket bucket;


TrustStore trustStore = TrustStore.Builder.create(this, "Store")
        .bucket(bucket)
        .key("rootCA_cert.pem")
        .build();

lb.addListener("Listener", BaseApplicationListenerProps.builder()
        .port(443)
        .protocol(ApplicationProtocol.HTTPS)
        .certificates(List.of(certificate))
        // mTLS settings
        .mutualAuthentication(MutualAuthentication.builder()
                .advertiseTrustStoreCaNames(true)
                .ignoreClientCertificateExpiry(false)
                .mutualAuthenticationMode(MutualAuthenticationMode.VERIFY)
                .trustStore(trustStore)
                .build())
        .defaultAction(ListenerAction.fixedResponse(200, FixedResponseOptions.builder().contentType("text/plain").messageBody("Success mTLS").build()))
        .build());
csharp
using Amazon.CDK.AWS.CertificateManager;

Certificate certificate;
ApplicationLoadBalancer lb;
Bucket bucket;


var trustStore = new TrustStore(this, "Store", new TrustStoreProps {
    Bucket = bucket,
    Key = "rootCA_cert.pem"
});

lb.AddListener("Listener", new BaseApplicationListenerProps {
    Port = 443,
    Protocol = ApplicationProtocol.HTTPS,
    Certificates = new [] { certificate },
    // mTLS settings
    MutualAuthentication = new MutualAuthentication {
        AdvertiseTrustStoreCaNames = true,
        IgnoreClientCertificateExpiry = false,
        MutualAuthenticationMode = MutualAuthenticationMode.VERIFY,
        TrustStore = trustStore
    },
    DefaultAction = ListenerAction.FixedResponse(200, new FixedResponseOptions { ContentType = "text/plain", MessageBody = "Success mTLS" })
});
go
import acm "github.com/aws/aws-cdk-go/awscdk"

var certificate Certificate
var lb ApplicationLoadBalancer
var bucket Bucket


trustStore := elbv2.NewTrustStore(this, jsii.String("Store"), &TrustStoreProps{
	Bucket: Bucket,
	Key: jsii.String("rootCA_cert.pem"),
})

lb.AddListener(jsii.String("Listener"), &BaseApplicationListenerProps{
	Port: jsii.Number(443),
	Protocol: elbv2.ApplicationProtocol_HTTPS,
	Certificates: []IListenerCertificate{
		certificate,
	},
	// mTLS settings
	MutualAuthentication: &MutualAuthentication{
		AdvertiseTrustStoreCaNames: jsii.Boolean(true),
		IgnoreClientCertificateExpiry: jsii.Boolean(false),
		MutualAuthenticationMode: elbv2.MutualAuthenticationMode_VERIFY,
		TrustStore: *TrustStore,
	},
	DefaultAction: elbv2.ListenerAction_FixedResponse(jsii.Number(200), &FixedResponseOptions{
		ContentType: jsii.String("text/plain"),
		MessageBody: jsii.String("Success mTLS"),
	}),
})

Optionally, you can create a certificate revocation list for a trust store by creating an instance of TrustStoreRevocation.

ts
declare const trustStore: elbv2.TrustStore;
declare const bucket: s3.Bucket;

new elbv2.TrustStoreRevocation(this, 'Revocation', {
  trustStore,
  revocationContents: [
    {
      revocationType: elbv2.RevocationType.CRL,
      bucket,
      key: 'crl.pem',
    },
  ],
});
python
# trust_store: elbv2.TrustStore
# bucket: s3.Bucket


elbv2.TrustStoreRevocation(self, "Revocation",
    trust_store=trust_store,
    revocation_contents=[elbv2.RevocationContent(
        revocation_type=elbv2.RevocationType.CRL,
        bucket=bucket,
        key="crl.pem"
    )
    ]
)
java
TrustStore trustStore;
Bucket bucket;


TrustStoreRevocation.Builder.create(this, "Revocation")
        .trustStore(trustStore)
        .revocationContents(List.of(RevocationContent.builder()
                .revocationType(RevocationType.CRL)
                .bucket(bucket)
                .key("crl.pem")
                .build()))
        .build();
csharp
TrustStore trustStore;
Bucket bucket;


new TrustStoreRevocation(this, "Revocation", new TrustStoreRevocationProps {
    TrustStore = trustStore,
    RevocationContents = new [] { new RevocationContent {
        RevocationType = RevocationType.CRL,
        Bucket = bucket,
        Key = "crl.pem"
    } }
});
go
var trustStore TrustStore
var bucket Bucket


elbv2.NewTrustStoreRevocation(this, jsii.String("Revocation"), &TrustStoreRevocationProps{
	TrustStore: TrustStore,
	RevocationContents: []RevocationContent{
		&RevocationContent{
			RevocationType: elbv2.RevocationType_CRL,
			Bucket: *Bucket,
			Key: jsii.String("crl.pem"),
		},
	},
})

Types ​

NameKindSummary
ApplicationListenerConstruct (L2)Define an ApplicationListener.
ApplicationLoadBalancerConstruct (L2)Define an Application Load Balancer.
BaseListenerConstruct (L2)Base class for listeners.
BaseLoadBalancerConstruct (L2)Base class for both Application and Network Load Balancers.
NetworkListenerConstruct (L2)Define a Network Listener.
NetworkLoadBalancerConstruct (L2)Define a new network load balancer.
TrustStoreConstruct (L2)A new Trust Store.
TrustStoreRevocationConstruct (L2)A new Trust Store Revocation.
CfnListenerConstruct (L1)Specifies a listener for an Application Load Balancer, Network Load Balancer, or Gateway Load Balancer.
CfnListenerCertificateConstruct (L1)Specifies an SSL server certificate to add to the certificate list for an HTTPS or TLS listener.
CfnListenerRuleConstruct (L1)Specifies a listener rule.
CfnLoadBalancerConstruct (L1)Specifies an Application Load Balancer, a Network Load Balancer, or a Gateway Load Balancer.
CfnTargetGroupConstruct (L1)Specifies a target group for an Application Load Balancer, a Network Load Balancer, or a Gateway Load Balancer.
CfnTrustStoreConstruct (L1)Creates a trust store.
CfnTrustStoreRevocationConstruct (L1)Adds the specified revocation contents to the specified trust store.
AddApplicationActionPropsStructProperties for adding a new action to a listener.
AddApplicationTargetGroupsPropsStructProperties for adding a new target group to a listener.
AddApplicationTargetsPropsStructProperties for adding new targets to a listener.
AddNetworkActionPropsStructProperties for adding a new action to a listener.
AddNetworkTargetsPropsStructProperties for adding new network targets to a listener.
AddRulePropsStructProperties for adding a conditional load balancing rule.
AlpnPolicyEnumApplication-Layer Protocol Negotiation Policies for network load balancers.
ApplicationListenerAttributesStructProperties to reference an existing listener.
ApplicationListenerCertificateConstructAdd certificates to a listener.
ApplicationListenerCertificatePropsStructProperties for adding a set of certificates to a listener.
ApplicationListenerLookupOptionsStructOptions for ApplicationListener lookup.
ApplicationListenerPropsStructProperties for defining a standalone ApplicationListener.
ApplicationListenerRuleConstructDefine a new listener rule.
ApplicationListenerRulePropsStructProperties for defining a listener rule.
ApplicationLoadBalancerAttributesStructProperties to reference an existing load balancer.
ApplicationLoadBalancerLookupOptionsStructOptions for looking up an ApplicationLoadBalancer.
ApplicationLoadBalancerPropsStructProperties for defining an Application Load Balancer.
ApplicationLoadBalancerRedirectConfigStructProperties for a redirection config.
ApplicationProtocolEnumLoad balancing protocol for application load balancers.
ApplicationProtocolVersionEnumLoad balancing protocol version for application load balancers.
ApplicationTargetGroupConstructDefine an Application Target Group.
ApplicationTargetGroupPropsStructProperties for defining an Application Target Group.
AuthenticateJwtOptionsStructOptions for ListenerAction.authenticateJwt().
AuthenticateOidcOptionsStructOptions for ListenerAction.authenciateOidc().
BaseApplicationListenerPropsStructBasic properties for an ApplicationListener.
BaseApplicationListenerRulePropsStructBasic properties for defining a rule on a listener.
BaseListenerLookupOptionsStructOptions for listener lookup.
BaseLoadBalancerLookupOptionsStructOptions for looking up load balancers.
BaseLoadBalancerPropsStructShared properties of both Application and Network Load Balancers.
BaseNetworkListenerPropsStructBasic properties for a Network Listener.
BaseTargetGroupPropsStructBasic properties of both Application and Network Target Groups.
CfnListener.ActionPropertyStructSpecifies an action for a listener rule.
CfnListener.AuthenticateCognitoConfigPropertyStructSpecifies information required when integrating with Amazon Cognito to authenticate users.
CfnListener.AuthenticateOidcConfigPropertyStructSpecifies information required using an identity provide (IdP) that is compliant with OpenID Connect (OIDC) to authenticate users.
CfnListener.CertificatePropertyStructSpecifies an SSL server certificate to use as the default certificate for a secure listener.
CfnListener.FixedResponseConfigPropertyStructSpecifies information required when returning a custom HTTP response.
CfnListener.ForwardConfigPropertyStructInformation for creating an action that distributes requests among multiple target groups. Specify only when Type is forward .
CfnListener.JwtValidationActionAdditionalClaimPropertyStructInformation about an additional claim to validate.
CfnListener.JwtValidationConfigPropertyStruct
CfnListener.ListenerAttributePropertyStructInformation about a listener attribute.
CfnListener.MutualAuthenticationPropertyStructThe mutual authentication configuration information.
CfnListener.RedirectConfigPropertyStructInformation about a redirect action.
CfnListener.TargetGroupStickinessConfigPropertyStructInformation about the target group stickiness for a rule.
CfnListener.TargetGroupTuplePropertyStructInformation about how traffic will be distributed between multiple target groups in a forward rule.
CfnListenerCertificate.CertificatePropertyStructSpecifies an SSL server certificate for the certificate list of a secure listener.
CfnListenerCertificatePropsStructProperties for defining a CfnListenerCertificate.
CfnListenerPropsStructProperties for defining a CfnListener.
CfnListenerRule.ActionPropertyStructSpecifies an action for a listener rule.
CfnListenerRule.AuthenticateCognitoConfigPropertyStructSpecifies information required when integrating with Amazon Cognito to authenticate users.
CfnListenerRule.AuthenticateOidcConfigPropertyStructSpecifies information required using an identity provide (IdP) that is compliant with OpenID Connect (OIDC) to authenticate users.
CfnListenerRule.FixedResponseConfigPropertyStructSpecifies information required when returning a custom HTTP response.
CfnListenerRule.ForwardConfigPropertyStructInformation for creating an action that distributes requests among multiple target groups. Specify only when Type is forward .
CfnListenerRule.HostHeaderConfigPropertyStructInformation about a host header condition.
CfnListenerRule.HttpHeaderConfigPropertyStructInformation about an HTTP header condition.
CfnListenerRule.HttpRequestMethodConfigPropertyStructInformation about an HTTP method condition.
CfnListenerRule.JwtValidationActionAdditionalClaimPropertyStructInformation about an additional claim to validate.
CfnListenerRule.JwtValidationConfigPropertyStruct
CfnListenerRule.PathPatternConfigPropertyStructInformation about a path pattern condition.
CfnListenerRule.QueryStringConfigPropertyStructInformation about a query string condition.
CfnListenerRule.QueryStringKeyValuePropertyStructInformation about a key/value pair.
CfnListenerRule.RedirectConfigPropertyStructInformation about a redirect action.
CfnListenerRule.RewriteConfigObjectPropertyStruct
CfnListenerRule.RewriteConfigPropertyStructInformation about a rewrite transform.
CfnListenerRule.RuleConditionPropertyStructSpecifies a condition for a listener rule.
CfnListenerRule.SourceIpConfigPropertyStructInformation about a source IP condition.
CfnListenerRule.TargetGroupStickinessConfigPropertyStructInformation about the target group stickiness for a rule.
CfnListenerRule.TargetGroupTuplePropertyStructInformation about how traffic will be distributed between multiple target groups in a forward rule.
CfnListenerRule.TransformPropertyStruct
CfnListenerRulePropsStructProperties for defining a CfnListenerRule.
CfnLoadBalancer.LoadBalancerAttributePropertyStructSpecifies an attribute for an Application Load Balancer, a Network Load Balancer, or a Gateway Load Balancer.
CfnLoadBalancer.MinimumLoadBalancerCapacityPropertyStructThe minimum capacity for a load balancer.
CfnLoadBalancer.SubnetMappingPropertyStructSpecifies a subnet for a load balancer.
CfnLoadBalancerPropsStructProperties for defining a CfnLoadBalancer.
CfnTargetGroup.MatcherPropertyStructSpecifies the HTTP codes that healthy targets must use when responding to an HTTP health check.
CfnTargetGroup.TargetDescriptionPropertyStructSpecifies a target to add to a target group.
CfnTargetGroup.TargetGroupAttributePropertyStructSpecifies a target group attribute.
CfnTargetGroupPropsStructProperties for defining a CfnTargetGroup.
CfnTrustStorePropsStructProperties for defining a CfnTrustStore.
CfnTrustStoreRevocation.RevocationContentPropertyStructInformation about a revocation file.
CfnTrustStoreRevocation.TrustStoreRevocationPropertyStructInformation about a revocation file in use by a trust store.
CfnTrustStoreRevocationPropsStructProperties for defining a CfnTrustStoreRevocation.
ClientRoutingPolicyEnumIndicates how traffic is distributed among the load balancer Availability Zones.
DesyncMitigationModeEnumHow the load balancer handles requests that might pose a security risk to your application.
FixedResponseOptionsStructOptions for ListenerAction.fixedResponse().
ForwardOptionsStructOptions for ListenerAction.forward().
HealthCheckStructProperties for configuring a health check.
HttpCodeElbEnumCount of HTTP status originating from the load balancer.
HttpCodeTargetEnumCount of HTTP status originating from the targets.
IApplicationListenerInterfaceProperties to reference an existing listener.
IApplicationListenerRefInterfaceIndicates that this resource can be referenced as an ALB Listener.
IApplicationLoadBalancerInterfaceAn application load balancer.
IApplicationLoadBalancerMetricsInterfaceContains all metrics for an Application Load Balancer.
IApplicationLoadBalancerRefInterfaceIndicates that this resource can be referenced as an Application LoadBalancer.
IApplicationLoadBalancerTargetInterfaceInterface for constructs that can be targets of an application load balancer.
IApplicationTargetGroupInterfaceA Target Group for Application Load Balancers.
IApplicationTargetGroupMetricsInterfaceContains all metrics for a Target Group of a Application Load Balancer.
IListenerInterfaceBase interface for listeners.
IListenerActionInterfaceInterface for listener actions.
IListenerCertificateInterfaceA certificate source for an ELBv2 listener.
ILoadBalancerV2Interface
INetworkListenerInterfaceProperties to reference an existing listener.
INetworkListenerRefInterfaceIndicates that this resource can be referenced as an NLB Listener.
INetworkLoadBalancerInterfaceA network load balancer.
INetworkLoadBalancerMetricsInterfaceContains all metrics for a Network Load Balancer.
INetworkLoadBalancerTargetInterfaceInterface for constructs that can be targets of an network load balancer.
INetworkTargetGroupInterfaceA network target group.
INetworkTargetGroupMetricsInterfaceContains all metrics for a Target Group of a Network Load Balancer.
INetworkTargetGroupRefInterfaceIndicates that this resource can be referenced as an NLB TargetGroup.
IpAddressTypeEnumWhat kind of addresses to allocate to the load balancer.
ITargetGroupInterfaceA target group.
ITrustStoreInterfaceRepresents a Trust Store.
ListenerActionClassWhat to do when a client makes a request to a listener.
ListenerCertificateClassA certificate source for an ELBv2 listener.
ListenerConditionClassListenerCondition providers definition.
LoadBalancerTargetPropsStructResult of attaching a target to load balancer.
MutualAuthenticationStructThe mutual authentication configuration information.
MutualAuthenticationModeEnumThe client certificate handling method.
NetworkForwardOptionsStructOptions for NetworkListenerAction.forward().
NetworkListenerActionClassWhat to do when a client makes a request to a listener.
NetworkListenerLookupOptionsStructOptions for looking up a network listener.
NetworkListenerPropsStructProperties for a Network Listener attached to a Load Balancer.
NetworkLoadBalancerAttributesStructProperties to reference an existing load balancer.
NetworkLoadBalancerLookupOptionsStructOptions for looking up an NetworkLoadBalancer.
NetworkLoadBalancerPropsStructProperties for a network load balancer.
NetworkTargetGroupConstructDefine a Network Target Group.
NetworkTargetGroupPropsStructProperties for a new Network Target Group.
NetworkWeightedTargetGroupStructA Target Group and weight combination.
ProtocolEnumBackend protocol for network load balancers and health checks.
QueryStringConditionStructProperties for the key/value pair of the query string.
RedirectOptionsStructOptions for ListenerAction.redirect().
RevocationContentStructInformation about a revocation file.
RevocationTypeEnumThe type of revocation file.
SourceNatIpv6PrefixClassThe prefix to use for source NAT for a dual-stack network load balancer with UDP listeners.
SslPolicyEnumElastic Load Balancing provides the following security policies for Application Load Balancers.
SubnetMappingStructSpecifies a subnet for a load balancer.
TargetGroupAttributesStructProperties to reference an existing target group.
TargetGroupBaseConstructDefine the target of a load balancer.
TargetGroupHealthStructProperties for configuring a target group health.
TargetGroupIpAddressTypeEnumThe IP address type of targets registered with a target group.
TargetGroupLoadBalancingAlgorithmTypeEnumLoad balancing algorithmm type for target groups.
TargetTypeEnumHow to interpret the load balancing target identifiers.
TrustStorePropsStructProperties used for the Trust Store.
TrustStoreRevocationPropsStructProperties for the trust store revocation.
UnauthenticatedActionEnumWhat to do with unauthenticated requests.
WeightedTargetGroupStructA Target Group and weight combination.
XffHeaderProcessingModeEnumProcessing mode of the X-Forwarded-For header in the HTTP request before the Application Load Balancer sends the request to the target.