Package software.amazon.awscdk.services.elasticloadbalancingv2
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:
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());
The security groups of the load balancer and the target are automatically updated to allow the network traffic.
One (or more) security groups can be associated with the load balancer; if a security group isn't provided, one will be automatically created.
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);
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
:
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());
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 astickinessDuration
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 (see theaws-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:
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());
Here's an example of using OIDC authentication before forwarding to a TargetGroup:
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());
If you just want to redirect all incoming traffic on one port to another port, you can use the following code:
ApplicationLoadBalancer lb; lb.addRedirect(ApplicationLoadBalancerRedirectConfig.builder() .sourceProtocol(ApplicationProtocol.HTTPS) .sourcePort(8443) .targetProtocol(ApplicationProtocol.HTTP) .targetPort(8080) .build());
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:
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 thatare 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();
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
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);
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
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);
Dualstack Application Load Balancer
You can create a dualstack Network Load Balancer using the ipAddressType
property:
Vpc vpc; ApplicationLoadBalancer lb = ApplicationLoadBalancer.Builder.create(this, "LB") .vpc(vpc) .ipAddressType(IpAddressType.DUAL_STACK) .build();
By setting DUAL_STACK_WITHOUT_PUBLIC_IPV4
, you can provision load balancers without public IPv4s
Vpc vpc; ApplicationLoadBalancer lb = ApplicationLoadBalancer.Builder.create(this, "LB") .vpc(vpc) .ipAddressType(IpAddressType.DUAL_STACK_WITHOUT_PUBLIC_IPV4) .build();
Defining a Network Load Balancer
Network Load Balancers are defined in a similar way to Application Load Balancers:
Vpc vpc; AutoScalingGroup asg; ISecurityGroup sg1; ISecurityGroup sg2; // 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) .securityGroups(List.of(sg1)) .build(); lb.addSecurityGroup(sg2); // 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());
Enforce security group inbound rules on PrivateLink traffic for a Network Load Balancer
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.
Vpc vpc; NetworkLoadBalancer nlb = NetworkLoadBalancer.Builder.create(this, "LB") .vpc(vpc) .enforceSecurityGroupInboundRulesOnPrivateLinkTraffic(true) .build();
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:
Vpc vpc; NetworkLoadBalancer lb = NetworkLoadBalancer.Builder.create(this, "LB") .vpc(vpc) .ipAddressType(IpAddressType.DUAL_STACK) .build();
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.
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());
Network Load Balancer attributes
You can modify attributes of Network Load Balancers:
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();
Network Load Balancer Listener attributes
You can modify attributes of Network Load Balancer Listener:
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());
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.
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));
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:
NetworkListener listener; AutoScalingGroup asg1; AutoScalingGroup asg2; NetworkTargetGroup group = listener.addTargets("AppFleet", AddNetworkTargetsProps.builder() .port(443) .targets(List.of(asg1)) .build()); 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.
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();
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).
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();
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.
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();
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).
Vpc vpc; ApplicationTargetGroup tg = ApplicationTargetGroup.Builder.create(this, "TargetGroup") .vpc(vpc) .loadBalancingAlgorithmType(TargetGroupLoadBalancingAlgorithmType.WEIGHTED_RANDOM) .enableAnomalyMitigation(true) .build();
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 infomation, see How Elastic Load Balancing works.
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();
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.
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();
Using Lambda Targets
To use a Lambda Function as a target, use the integration class in the
aws-cdk-lib/aws-elasticloadbalancingv2-targets
package:
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());
Only a single Lambda function can be added to a single listener rule.
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:
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();
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:
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());
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:
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));
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:
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(); } }
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:
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());
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
IApplicationLoadBalancer loadBalancer = ApplicationLoadBalancer.fromLookup(this, "ALB", ApplicationLoadBalancerLookupOptions.builder() .loadBalancerArn("arn:aws:elasticloadbalancing:us-east-2:123456789012:loadbalancer/app/my-load-balancer/1234567890123456") .build());
Look up an Application Load Balancer by tags
IApplicationLoadBalancer loadBalancer = ApplicationLoadBalancer.fromLookup(this, "ALB", ApplicationLoadBalancerLookupOptions.builder() .loadBalancerTags(Map.of( // Finds a load balancer matching all tags. "some", "tag", "someother", "tag")) .build());
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
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());
Look up a Listener by associated Load Balancer Tag, Port, and Protocol
IApplicationListener listener = ApplicationListener.fromLookup(this, "ALBListener", ApplicationListenerLookupOptions.builder() .loadBalancerTags(Map.of( "Cluster", "MyClusterName")) .listenerProtocol(ApplicationProtocol.HTTPS) .listenerPort(443) .build());
Look up a Network Listener by associated Load Balancer Tag, Port, and Protocol
INetworkListener listener = NetworkListener.fromLookup(this, "ALBListener", NetworkListenerLookupOptions.builder() .loadBalancerTags(Map.of( "Cluster", "MyClusterName")) .listenerProtocol(Protocol.TCP) .listenerPort(12345) .build());
Metrics
You may create metrics for Load Balancers and Target Groups through the metrics
attribute:
Load Balancer:
IApplicationLoadBalancer alb; IApplicationLoadBalancerMetrics albMetrics = alb.getMetrics(); Metric metricConnectionCount = albMetrics.activeConnectionCount();
Target Group:
IApplicationTargetGroup targetGroup; IApplicationTargetGroupMetrics targetGroupMetrics = targetGroup.getMetrics(); Metric metricHealthyHostCount = targetGroupMetrics.healthyHostCount();
Metrics are also available to imported resources:
Stack stack; IApplicationTargetGroup targetGroup = ApplicationTargetGroup.fromTargetGroupAttributes(this, "MyTargetGroup", TargetGroupAttributes.builder() .targetGroupArn(Fn.importValue("TargetGroupArn")) .loadBalancerArns(Fn.importValue("LoadBalancerArn")) .build()); IApplicationTargetGroupMetrics targetGroupMetrics = targetGroup.getMetrics();
Notice that TargetGroups must be imported by supplying the Load Balancer too, otherwise accessing the metrics
will
throw an error:
Stack stack; IApplicationTargetGroup targetGroup = ApplicationTargetGroup.fromTargetGroupAttributes(this, "MyTargetGroup", TargetGroupAttributes.builder() .targetGroupArn(Fn.importValue("TargetGroupArn")) .build()); IApplicationTargetGroupMetrics targetGroupMetrics = targetGroup.getMetrics();
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 ListenerRule
s using addTargetGroups()
the recommendation
is to set the removeRuleSuffixFromLogicalId: false
property.
If you have ListenerRule
s 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.
ListenerRule
s 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
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() .ignoreClientCertificateExpiry(false) .mutualAuthenticationMode(MutualAuthenticationMode.VERIFY) .trustStore(trustStore) .build()) .defaultAction(ListenerAction.fixedResponse(200, FixedResponseOptions.builder().contentType("text/plain").messageBody("Success mTLS").build())) .build());
Optionally, you can create a certificate revocation list for a trust store by creating an instance of TrustStoreRevocation
.
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();
-
ClassDescriptionProperties for adding a new action to a listener.A builder for
AddApplicationActionProps
An implementation forAddApplicationActionProps
Properties for adding a new target group to a listener.A builder forAddApplicationTargetGroupsProps
An implementation forAddApplicationTargetGroupsProps
Properties for adding new targets to a listener.A builder forAddApplicationTargetsProps
An implementation forAddApplicationTargetsProps
Properties for adding a new action to a listener.A builder forAddNetworkActionProps
An implementation forAddNetworkActionProps
Properties for adding new network targets to a listener.A builder forAddNetworkTargetsProps
An implementation forAddNetworkTargetsProps
Properties for adding a conditional load balancing rule.A builder forAddRuleProps
An implementation forAddRuleProps
Application-Layer Protocol Negotiation Policies for network load balancers.Define an ApplicationListener.A fluent builder forApplicationListener
.Properties to reference an existing listener.A builder forApplicationListenerAttributes
An implementation forApplicationListenerAttributes
Add certificates to a listener.A fluent builder forApplicationListenerCertificate
.Properties for adding a set of certificates to a listener.A builder forApplicationListenerCertificateProps
An implementation forApplicationListenerCertificateProps
Options for ApplicationListener lookup.A builder forApplicationListenerLookupOptions
An implementation forApplicationListenerLookupOptions
Properties for defining a standalone ApplicationListener.A builder forApplicationListenerProps
An implementation forApplicationListenerProps
Define a new listener rule.A fluent builder forApplicationListenerRule
.Properties for defining a listener rule.A builder forApplicationListenerRuleProps
An implementation forApplicationListenerRuleProps
Define an Application Load Balancer.A fluent builder forApplicationLoadBalancer
.Properties to reference an existing load balancer.A builder forApplicationLoadBalancerAttributes
An implementation forApplicationLoadBalancerAttributes
Options for looking up an ApplicationLoadBalancer.A builder forApplicationLoadBalancerLookupOptions
An implementation forApplicationLoadBalancerLookupOptions
Properties for defining an Application Load Balancer.A builder forApplicationLoadBalancerProps
An implementation forApplicationLoadBalancerProps
Properties for a redirection config.A builder forApplicationLoadBalancerRedirectConfig
An implementation forApplicationLoadBalancerRedirectConfig
Load balancing protocol for application load balancers.Load balancing protocol version for application load balancers.Define an Application Target Group.A fluent builder forApplicationTargetGroup
.Properties for defining an Application Target Group.A builder forApplicationTargetGroupProps
An implementation forApplicationTargetGroupProps
Options forListenerAction.authenciateOidc()
.A builder forAuthenticateOidcOptions
An implementation forAuthenticateOidcOptions
Basic properties for an ApplicationListener.A builder forBaseApplicationListenerProps
An implementation forBaseApplicationListenerProps
Basic properties for defining a rule on a listener.A builder forBaseApplicationListenerRuleProps
An implementation forBaseApplicationListenerRuleProps
Base class for listeners.Options for listener lookup.A builder forBaseListenerLookupOptions
An implementation forBaseListenerLookupOptions
Base class for both Application and Network Load Balancers.Options for looking up load balancers.A builder forBaseLoadBalancerLookupOptions
An implementation forBaseLoadBalancerLookupOptions
Shared properties of both Application and Network Load Balancers.A builder forBaseLoadBalancerProps
An implementation forBaseLoadBalancerProps
Basic properties for a Network Listener.A builder forBaseNetworkListenerProps
An implementation forBaseNetworkListenerProps
Basic properties of both Application and Network Target Groups.A builder forBaseTargetGroupProps
An implementation forBaseTargetGroupProps
Specifies a listener for an Application Load Balancer, Network Load Balancer, or Gateway Load Balancer.Specifies an action for a listener rule.A builder forCfnListener.ActionProperty
An implementation forCfnListener.ActionProperty
Specifies information required when integrating with Amazon Cognito to authenticate users.A builder forCfnListener.AuthenticateCognitoConfigProperty
An implementation forCfnListener.AuthenticateCognitoConfigProperty
Specifies information required using an identity provide (IdP) that is compliant with OpenID Connect (OIDC) to authenticate users.A builder forCfnListener.AuthenticateOidcConfigProperty
An implementation forCfnListener.AuthenticateOidcConfigProperty
A fluent builder forCfnListener
.Specifies an SSL server certificate to use as the default certificate for a secure listener.A builder forCfnListener.CertificateProperty
An implementation forCfnListener.CertificateProperty
Specifies information required when returning a custom HTTP response.A builder forCfnListener.FixedResponseConfigProperty
An implementation forCfnListener.FixedResponseConfigProperty
Information for creating an action that distributes requests among one or more target groups.A builder forCfnListener.ForwardConfigProperty
An implementation forCfnListener.ForwardConfigProperty
Information about a listener attribute.A builder forCfnListener.ListenerAttributeProperty
An implementation forCfnListener.ListenerAttributeProperty
Specifies the configuration information for mutual authentication.A builder forCfnListener.MutualAuthenticationProperty
An implementation forCfnListener.MutualAuthenticationProperty
Information about a redirect action.A builder forCfnListener.RedirectConfigProperty
An implementation forCfnListener.RedirectConfigProperty
Information about the target group stickiness for a rule.A builder forCfnListener.TargetGroupStickinessConfigProperty
An implementation forCfnListener.TargetGroupStickinessConfigProperty
Information about how traffic will be distributed between multiple target groups in a forward rule.A builder forCfnListener.TargetGroupTupleProperty
An implementation forCfnListener.TargetGroupTupleProperty
Specifies an SSL server certificate to add to the certificate list for an HTTPS or TLS listener.A fluent builder forCfnListenerCertificate
.Specifies an SSL server certificate for the certificate list of a secure listener.A builder forCfnListenerCertificate.CertificateProperty
An implementation forCfnListenerCertificate.CertificateProperty
Properties for defining aCfnListenerCertificate
.A builder forCfnListenerCertificateProps
An implementation forCfnListenerCertificateProps
Properties for defining aCfnListener
.A builder forCfnListenerProps
An implementation forCfnListenerProps
Specifies a listener rule.Specifies an action for a listener rule.A builder forCfnListenerRule.ActionProperty
An implementation forCfnListenerRule.ActionProperty
Specifies information required when integrating with Amazon Cognito to authenticate users.A builder forCfnListenerRule.AuthenticateCognitoConfigProperty
An implementation forCfnListenerRule.AuthenticateCognitoConfigProperty
Specifies information required using an identity provide (IdP) that is compliant with OpenID Connect (OIDC) to authenticate users.A builder forCfnListenerRule.AuthenticateOidcConfigProperty
An implementation forCfnListenerRule.AuthenticateOidcConfigProperty
A fluent builder forCfnListenerRule
.Specifies information required when returning a custom HTTP response.A builder forCfnListenerRule.FixedResponseConfigProperty
An implementation forCfnListenerRule.FixedResponseConfigProperty
Information for creating an action that distributes requests among one or more target groups.A builder forCfnListenerRule.ForwardConfigProperty
An implementation forCfnListenerRule.ForwardConfigProperty
Information about a host header condition.A builder forCfnListenerRule.HostHeaderConfigProperty
An implementation forCfnListenerRule.HostHeaderConfigProperty
Information about an HTTP header condition.A builder forCfnListenerRule.HttpHeaderConfigProperty
An implementation forCfnListenerRule.HttpHeaderConfigProperty
Information about an HTTP method condition.A builder forCfnListenerRule.HttpRequestMethodConfigProperty
An implementation forCfnListenerRule.HttpRequestMethodConfigProperty
Information about a path pattern condition.A builder forCfnListenerRule.PathPatternConfigProperty
An implementation forCfnListenerRule.PathPatternConfigProperty
Information about a query string condition.A builder forCfnListenerRule.QueryStringConfigProperty
An implementation forCfnListenerRule.QueryStringConfigProperty
Information about a key/value pair.A builder forCfnListenerRule.QueryStringKeyValueProperty
An implementation forCfnListenerRule.QueryStringKeyValueProperty
Information about a redirect action.A builder forCfnListenerRule.RedirectConfigProperty
An implementation forCfnListenerRule.RedirectConfigProperty
Specifies a condition for a listener rule.A builder forCfnListenerRule.RuleConditionProperty
An implementation forCfnListenerRule.RuleConditionProperty
Information about a source IP condition.A builder forCfnListenerRule.SourceIpConfigProperty
An implementation forCfnListenerRule.SourceIpConfigProperty
Information about the target group stickiness for a rule.A builder forCfnListenerRule.TargetGroupStickinessConfigProperty
An implementation forCfnListenerRule.TargetGroupStickinessConfigProperty
Information about how traffic will be distributed between multiple target groups in a forward rule.A builder forCfnListenerRule.TargetGroupTupleProperty
An implementation forCfnListenerRule.TargetGroupTupleProperty
Properties for defining aCfnListenerRule
.A builder forCfnListenerRuleProps
An implementation forCfnListenerRuleProps
Specifies an Application Load Balancer, a Network Load Balancer, or a Gateway Load Balancer.A fluent builder forCfnLoadBalancer
.Specifies an attribute for an Application Load Balancer, a Network Load Balancer, or a Gateway Load Balancer.A builder forCfnLoadBalancer.LoadBalancerAttributeProperty
An implementation forCfnLoadBalancer.LoadBalancerAttributeProperty
The minimum capacity for a load balancer.A builder forCfnLoadBalancer.MinimumLoadBalancerCapacityProperty
An implementation forCfnLoadBalancer.MinimumLoadBalancerCapacityProperty
Specifies a subnet for a load balancer.A builder forCfnLoadBalancer.SubnetMappingProperty
An implementation forCfnLoadBalancer.SubnetMappingProperty
Properties for defining aCfnLoadBalancer
.A builder forCfnLoadBalancerProps
An implementation forCfnLoadBalancerProps
Specifies a target group for an Application Load Balancer, a Network Load Balancer, or a Gateway Load Balancer.A fluent builder forCfnTargetGroup
.Specifies the HTTP codes that healthy targets must use when responding to an HTTP health check.A builder forCfnTargetGroup.MatcherProperty
An implementation forCfnTargetGroup.MatcherProperty
Specifies a target to add to a target group.A builder forCfnTargetGroup.TargetDescriptionProperty
An implementation forCfnTargetGroup.TargetDescriptionProperty
Specifies a target group attribute.A builder forCfnTargetGroup.TargetGroupAttributeProperty
An implementation forCfnTargetGroup.TargetGroupAttributeProperty
Properties for defining aCfnTargetGroup
.A builder forCfnTargetGroupProps
An implementation forCfnTargetGroupProps
Creates a trust store.A fluent builder forCfnTrustStore
.Properties for defining aCfnTrustStore
.A builder forCfnTrustStoreProps
An implementation forCfnTrustStoreProps
Adds the specified revocation contents to the specified trust store.A fluent builder forCfnTrustStoreRevocation
.Information about a revocation file.A builder forCfnTrustStoreRevocation.RevocationContentProperty
An implementation forCfnTrustStoreRevocation.RevocationContentProperty
Information about a revocation file in use by a trust store.A builder forCfnTrustStoreRevocation.TrustStoreRevocationProperty
An implementation forCfnTrustStoreRevocation.TrustStoreRevocationProperty
Properties for defining aCfnTrustStoreRevocation
.A builder forCfnTrustStoreRevocationProps
An implementation forCfnTrustStoreRevocationProps
Indicates how traffic is distributed among the load balancer Availability Zones.How the load balancer handles requests that might pose a security risk to your application.Options forListenerAction.fixedResponse()
.A builder forFixedResponseOptions
An implementation forFixedResponseOptions
Options forListenerAction.forward()
.A builder forForwardOptions
An implementation forForwardOptions
Properties for configuring a health check.A builder forHealthCheck
An implementation forHealthCheck
Count of HTTP status originating from the load balancer.Count of HTTP status originating from the targets.Properties to reference an existing listener.Internal default implementation forIApplicationListener
.A proxy class which represents a concrete javascript instance of this type.An application load balancer.Internal default implementation forIApplicationLoadBalancer
.A proxy class which represents a concrete javascript instance of this type.Contains all metrics for an Application Load Balancer.Internal default implementation forIApplicationLoadBalancerMetrics
.A proxy class which represents a concrete javascript instance of this type.Interface for constructs that can be targets of an application load balancer.Internal default implementation forIApplicationLoadBalancerTarget
.A proxy class which represents a concrete javascript instance of this type.A Target Group for Application Load Balancers.Internal default implementation forIApplicationTargetGroup
.A proxy class which represents a concrete javascript instance of this type.Contains all metrics for a Target Group of a Application Load Balancer.Internal default implementation forIApplicationTargetGroupMetrics
.A proxy class which represents a concrete javascript instance of this type.Base interface for listeners.Internal default implementation forIListener
.A proxy class which represents a concrete javascript instance of this type.Interface for listener actions.Internal default implementation forIListenerAction
.A proxy class which represents a concrete javascript instance of this type.A certificate source for an ELBv2 listener.Internal default implementation forIListenerCertificate
.A proxy class which represents a concrete javascript instance of this type.Internal default implementation forILoadBalancerV2
.A proxy class which represents a concrete javascript instance of this type.Properties to reference an existing listener.Internal default implementation forINetworkListener
.A proxy class which represents a concrete javascript instance of this type.A network load balancer.Internal default implementation forINetworkLoadBalancer
.A proxy class which represents a concrete javascript instance of this type.Contains all metrics for a Network Load Balancer.Internal default implementation forINetworkLoadBalancerMetrics
.A proxy class which represents a concrete javascript instance of this type.Interface for constructs that can be targets of an network load balancer.Internal default implementation forINetworkLoadBalancerTarget
.A proxy class which represents a concrete javascript instance of this type.A network target group.Internal default implementation forINetworkTargetGroup
.A proxy class which represents a concrete javascript instance of this type.Contains all metrics for a Target Group of a Network Load Balancer.Internal default implementation forINetworkTargetGroupMetrics
.A proxy class which represents a concrete javascript instance of this type.What kind of addresses to allocate to the load balancer.A target group.Internal default implementation forITargetGroup
.A proxy class which represents a concrete javascript instance of this type.Represents a Trust Store.Internal default implementation forITrustStore
.A proxy class which represents a concrete javascript instance of this type.What to do when a client makes a request to a listener.A certificate source for an ELBv2 listener.ListenerCondition providers definition.Result of attaching a target to load balancer.A builder forLoadBalancerTargetProps
An implementation forLoadBalancerTargetProps
The mutual authentication configuration information.A builder forMutualAuthentication
An implementation forMutualAuthentication
The client certificate handling method.Options forNetworkListenerAction.forward()
.A builder forNetworkForwardOptions
An implementation forNetworkForwardOptions
Define a Network Listener.A fluent builder forNetworkListener
.What to do when a client makes a request to a listener.Options for looking up a network listener.A builder forNetworkListenerLookupOptions
An implementation forNetworkListenerLookupOptions
Properties for a Network Listener attached to a Load Balancer.A builder forNetworkListenerProps
An implementation forNetworkListenerProps
Define a new network load balancer.A fluent builder forNetworkLoadBalancer
.Properties to reference an existing load balancer.A builder forNetworkLoadBalancerAttributes
An implementation forNetworkLoadBalancerAttributes
Options for looking up an NetworkLoadBalancer.A builder forNetworkLoadBalancerLookupOptions
An implementation forNetworkLoadBalancerLookupOptions
Properties for a network load balancer.A builder forNetworkLoadBalancerProps
An implementation forNetworkLoadBalancerProps
Define a Network Target Group.A fluent builder forNetworkTargetGroup
.Properties for a new Network Target Group.A builder forNetworkTargetGroupProps
An implementation forNetworkTargetGroupProps
A Target Group and weight combination.A builder forNetworkWeightedTargetGroup
An implementation forNetworkWeightedTargetGroup
Backend protocol for network load balancers and health checks.Properties for the key/value pair of the query string.A builder forQueryStringCondition
An implementation forQueryStringCondition
Options forListenerAction.redirect()
.A builder forRedirectOptions
An implementation forRedirectOptions
Information about a revocation file.A builder forRevocationContent
An implementation forRevocationContent
The type of revocation file.Elastic Load Balancing provides the following security policies for Application Load Balancers.Properties to reference an existing target group.A builder forTargetGroupAttributes
An implementation forTargetGroupAttributes
Define the target of a load balancer.The IP address type of targets registered with a target group.Load balancing algorithmm type for target groups.How to interpret the load balancing target identifiers.A new Trust Store.A fluent builder forTrustStore
.Properties used for the Trust Store.A builder forTrustStoreProps
An implementation forTrustStoreProps
A new Trust Store Revocation.A fluent builder forTrustStoreRevocation
.Properties for the trust store revocation.A builder forTrustStoreRevocationProps
An implementation forTrustStoreRevocationProps
What to do with unauthenticated requests.A Target Group and weight combination.A builder forWeightedTargetGroup
An implementation forWeightedTargetGroup
Processing mode of the X-Forwarded-For header in the HTTP request before the Application Load Balancer sends the request to the target.