118 types
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.
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:
require 'aws-cdk-lib'
asg = nil # AWSCDK::Autoscaling::AutoScalingGroup
vpc = nil # AWSCDK::EC2::VPC
# Create the load balancer in a VPC. 'internetFacing' is 'false'
# by default, which creates an internal load balancer.
lb = AWSCDK::ElasticLoadBalancingv2::ApplicationLoadBalancer.new(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],
})
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:albDualstackWithoutPublicIpv4SecurityGroupRulesDefaultfeature flag is set (the default for new projects), andadd_listener()is called withopen: true, the load balancer's security group will automatically include both IPv4 and IPv6 ingress rules when usingIpAddressType.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.
vpc = nil # AWSCDK::EC2::VPC
security_group1 = AWSCDK::EC2::SecurityGroup.new(self, "SecurityGroup1", {vpc: vpc})
lb = AWSCDK::ElasticLoadBalancingv2::ApplicationLoadBalancer.new(self, "LB", {
vpc: vpc,
internet_facing: true,
security_group: security_group1,
})
security_group2 = AWSCDK::EC2::SecurityGroup.new(self, "SecurityGroup2", {vpc: vpc})
lb.add_security_group(security_group2)
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:
listener = nil # AWSCDK::ElasticLoadBalancingv2::ApplicationListener
asg = nil # AWSCDK::Autoscaling::AutoScalingGroup
listener.add_targets("Example.Com Fleet", {
priority: 10,
conditions: [
AWSCDK::ElasticLoadBalancingv2::ListenerCondition.host_headers(["example.com"]),
AWSCDK::ElasticLoadBalancingv2::ListenerCondition.path_patterns(["/ok", "/path"]),
],
port: 8080,
targets: [asg],
})
A target with a condition contains either path_patterns or host_header, 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.
Routing traffic from a Load Balancer to a Target involves the following steps:
A new listener can be added to the Load Balancer by calling add_listener().
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:
add_targets() performs both steps: automatically creates a Target Group and the
required Action.add_target_groups() 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.add_action() 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 add_action() gives you access to some of the features of an Elastic Load
Balancer that the other two convenience methods don't:
ListenerAction.forward() and supply a
stickiness_duration to make sure requests are routed to the same target group
for a given duration.ListenerAction.weightedForward()
to give different weights to different target groups.ListenerAction.fixedResponse() to serve
a static response (ALB only).ListenerAction.redirect() to serve an HTTP
redirect response (ALB only).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:
listener = nil # AWSCDK::ElasticLoadBalancingv2::ApplicationListener
listener.add_action("Fixed", {
priority: 10,
conditions: [
AWSCDK::ElasticLoadBalancingv2::ListenerCondition.path_patterns(["/ok"]),
],
action: AWSCDK::ElasticLoadBalancingv2::ListenerAction.fixed_response(200, {
content_type: "text/plain",
message_body: "OK",
}),
})
Here's an example of using OIDC authentication before forwarding to a TargetGroup:
listener = nil # AWSCDK::ElasticLoadBalancingv2::ApplicationListener
my_target_group = nil # AWSCDK::ElasticLoadBalancingv2::ApplicationTargetGroup
listener.add_action("DefaultAction", {
action: AWSCDK::ElasticLoadBalancingv2::ListenerAction.authenticate_oidc({
authorization_endpoint: "https://example.com/openid",
# Other OIDC properties here
client_id: "...",
client_secret: AWSCDK::SecretValue.secrets_manager("..."),
issuer: "...",
token_endpoint: "...",
user_info_endpoint: "...",
# Next
_next: AWSCDK::ElasticLoadBalancingv2::ListenerAction.forward([my_target_group]),
}),
})
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.
lb = nil # AWSCDK::ElasticLoadBalancingv2::ApplicationLoadBalancer
certificate = nil # AWSCDK::ElasticLoadBalancingv2::IListenerCertificate
my_target_group = nil # AWSCDK::ElasticLoadBalancingv2::ApplicationTargetGroup
# JWT authentication requires HTTPS
listener = lb.add_listener("Listener", {
protocol: AWSCDK::ElasticLoadBalancingv2::ApplicationProtocol::HTTPS,
port: 443,
certificates: [certificate],
default_action: AWSCDK::ElasticLoadBalancingv2::ListenerAction.authenticate_jwt({
issuer: "https://issuer.example.com",
jwks_endpoint: "https://issuer.example.com/.well-known/jwks.json",
_next: AWSCDK::ElasticLoadBalancingv2::ListenerAction.forward([my_target_group]),
}),
})
If you just want to redirect all incoming traffic on one port to another port, you can use the following code:
lb = nil # AWSCDK::ElasticLoadBalancingv2::ApplicationLoadBalancer
lb.add_redirect({
source_protocol: AWSCDK::ElasticLoadBalancingv2::ApplicationProtocol::HTTPS,
source_port: 8443,
target_protocol: AWSCDK::ElasticLoadBalancingv2::ApplicationProtocol::HTTP,
target_port: 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 /.
You can modify attributes of Application Load Balancers:
vpc = nil # AWSCDK::EC2::VPC
lb = AWSCDK::ElasticLoadBalancingv2::ApplicationLoadBalancer.new(self, "LB", {
vpc: vpc,
internet_facing: true,
# Whether HTTP/2 is enabled
http2_enabled: false,
# The idle timeout value, in seconds
idle_timeout: AWSCDK::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: AWSCDK::ElasticLoadBalancingv2::DesyncMitigationMode::DEFENSIVE,
# The type of IP addresses to use.
ip_address_type: AWSCDK::ElasticLoadBalancingv2::IPAddressType::IPV4,
# The duration of client keep-alive connections
client_keep_alive: AWSCDK::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: AWSCDK::ElasticLoadBalancingv2::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,
})
For more information, see Load balancer attributes
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 = nil # AWSCDK::EC2::VPC
bucket = AWSCDK::S3::Bucket.new(self, "ALBAccessLogsBucket", {
encryption: AWSCDK::S3::BucketEncryption::S3_MANAGED,
})
lb = AWSCDK::ElasticLoadBalancingv2::ApplicationLoadBalancer.new(self, "LB", {vpc: vpc})
lb.log_access_logs(bucket)
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 = nil # AWSCDK::EC2::VPC
bucket = AWSCDK::S3::Bucket.new(self, "ALBConnectionLogsBucket", {
encryption: AWSCDK::S3::BucketEncryption::S3_MANAGED,
})
lb = AWSCDK::ElasticLoadBalancingv2::ApplicationLoadBalancer.new(self, "LB", {vpc: vpc})
lb.log_connection_logs(bucket)
You can create a dualstack Network Load Balancer using the ip_address_type property:
vpc = nil # AWSCDK::EC2::VPC
lb = AWSCDK::ElasticLoadBalancingv2::ApplicationLoadBalancer.new(self, "LB", {
vpc: vpc,
ip_address_type: AWSCDK::ElasticLoadBalancingv2::IPAddressType::DUAL_STACK,
})
By setting DUAL_STACK_WITHOUT_PUBLIC_IPV4, you can provision load balancers without public IPv4s:
vpc = nil # AWSCDK::EC2::VPC
lb = AWSCDK::ElasticLoadBalancingv2::ApplicationLoadBalancer.new(self, "LB", {
vpc: vpc,
internet_facing: true,
ip_address_type: AWSCDK::ElasticLoadBalancingv2::IPAddressType::DUAL_STACK_WITHOUT_PUBLIC_IPV4,
})
You can define a reserved LCU for your Application Load Balancer.
To reserve an LCU, you must specify a minimum_capacity_unit.
vpc = nil # AWSCDK::EC2::VPC
lb = AWSCDK::ElasticLoadBalancingv2::ApplicationLoadBalancer.new(self, "LB", {
vpc: vpc,
# Valid value is between 100 and 1500.
minimum_capacity_unit: 100,
})
Network Load Balancers are defined in a similar way to Application Load Balancers:
vpc = nil # AWSCDK::EC2::VPC
asg = nil # AWSCDK::Autoscaling::AutoScalingGroup
# Create the load balancer in a VPC. 'internetFacing' is 'false'
# by default, which creates an internal load balancer.
lb = AWSCDK::ElasticLoadBalancingv2::NetworkLoadBalancer.new(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],
})
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 security_groups property.
If you wish to create an NLB without any security groups, you can set the disable_security_groups property to true. When this property is set, no security group will be associated with the NLB, regardless of the feature flag.
vpc = nil # AWSCDK::EC2::IVPC
nlb = AWSCDK::ElasticLoadBalancingv2::NetworkLoadBalancer.new(self, "LB", {
vpc: vpc,
# To disable security groups for this NLB
disable_security_groups: true,
})
If you want to use your own security groups, provide them via the security_groups property:
vpc = nil # AWSCDK::EC2::IVPC
sg1 = nil # AWSCDK::EC2::ISecurityGroup
sg2 = nil # AWSCDK::EC2::ISecurityGroup
nlb = AWSCDK::ElasticLoadBalancingv2::NetworkLoadBalancer.new(self, "LB", {
vpc: vpc,
# Provide your own security groups
security_groups: [sg1],
})
# Add another security group to the NLB
nlb.add_security_group(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.
vpc = nil # AWSCDK::EC2::VPC
nlb = AWSCDK::ElasticLoadBalancingv2::NetworkLoadBalancer.new(self, "LB", {
vpc: vpc,
enforce_security_group_inbound_rules_on_private_link_traffic: 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.
You can create a dualstack Network Load Balancer using the ip_address_type property:
vpc = nil # AWSCDK::EC2::VPC
lb = AWSCDK::ElasticLoadBalancingv2::NetworkLoadBalancer.new(self, "LB", {
vpc: vpc,
ip_address_type: AWSCDK::ElasticLoadBalancingv2::IPAddressType::DUAL_STACK,
})
You can configure whether to use an IPv6 prefix from each subnet for source NAT by setting enable_prefix_for_ipv6_source_nat to true.
This must be enabled if you want to create a dualstack Network Load Balancer with a listener that uses UDP protocol.
vpc = nil # AWSCDK::EC2::VPC
lb = AWSCDK::ElasticLoadBalancingv2::NetworkLoadBalancer.new(self, "LB", {
vpc: vpc,
ip_address_type: AWSCDK::ElasticLoadBalancingv2::IPAddressType::DUAL_STACK,
enable_prefix_for_ipv6_source_nat: true,
})
listener = lb.add_listener("Listener", {
port: 1229,
protocol: AWSCDK::ElasticLoadBalancingv2::Protocol::UDP,
})
You can specify the subnets for a Network Load Balancer easily by setting the vpc_subnets property.
vpc = nil # AWSCDK::EC2::VPC
lb = AWSCDK::ElasticLoadBalancingv2::NetworkLoadBalancer.new(self, "LB", {
vpc: vpc,
vpc_subnets: {
subnet_type: AWSCDK::EC2::SubnetType::PRIVATE,
},
})
If you want to configure detailed information about the subnets, you can use the subnet_mappings property as follows:
vpc = nil # AWSCDK::EC2::IVPC
dualstack_vpc = nil # AWSCDK::EC2::IVPC
subnet = nil # AWSCDK::EC2::ISubnet
dualstack_subnet = nil # AWSCDK::EC2::ISubnet
cfn_eip = nil # AWSCDK::EC2::CfnEIP
# Internet facing Network Load Balancer with an Elastic IPv4 address
AWSCDK::ElasticLoadBalancingv2::NetworkLoadBalancer.new(self, "InternetFacingLb", {
vpc: vpc,
internet_facing: true,
subnet_mappings: [
{
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
AWSCDK::ElasticLoadBalancingv2::NetworkLoadBalancer.new(self, "InternalLb", {
vpc: vpc,
internet_facing: false,
subnet_mappings: [
{
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
AWSCDK::ElasticLoadBalancingv2::NetworkLoadBalancer.new(self, "DualstackLb", {
vpc: dualstack_vpc,
# Configure the dualstack Network Load Balancer
ip_address_type: AWSCDK::ElasticLoadBalancingv2::IPAddressType::DUAL_STACK,
enable_prefix_for_ipv6_source_nat: true,
subnet_mappings: [
{
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: AWSCDK::ElasticLoadBalancingv2::SourceNatIpv6Prefix.auto_assigned,
},
],
})
You can modify attributes of Network Load Balancers:
vpc = nil # AWSCDK::EC2::VPC
lb = AWSCDK::ElasticLoadBalancingv2::NetworkLoadBalancer.new(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: AWSCDK::ElasticLoadBalancingv2::ClientRoutingPolicy::AVAILABILITY_ZONE_AFFINITY,
# Indicates whether zonal shift is enabled.
zonal_shift: true,
})
You can modify attributes of Network Load Balancer Listener:
lb = nil # AWSCDK::ElasticLoadBalancingv2::NetworkLoadBalancer
group = nil # AWSCDK::ElasticLoadBalancingv2::NetworkTargetGroup
listener = lb.add_listener("Listener", {
port: 80,
default_action: AWSCDK::ElasticLoadBalancingv2::NetworkListenerAction.forward([group]),
# The tcp idle timeout value. The valid range is 60-6000 seconds. The default is 350 seconds.
tcp_idle_timeout: AWSCDK::Duration.seconds(100),
})
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 = nil # AWSCDK::EC2::VPC
sg1 = nil # AWSCDK::EC2::ISecurityGroup
sg2 = nil # AWSCDK::EC2::ISecurityGroup
lb = AWSCDK::ElasticLoadBalancingv2::NetworkLoadBalancer.new(self, "LB", {
vpc: vpc,
internet_facing: true,
security_groups: [sg1],
})
lb.add_security_group(sg2)
lb.connections.allow_from_any_ipv4(AWSCDK::EC2::Port.tcp(80))
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 minimum_capacity_unit.
vpc = nil # AWSCDK::EC2::VPC
lb = AWSCDK::ElasticLoadBalancingv2::NetworkLoadBalancer.new(self, "LB", {
vpc: vpc,
minimum_capacity_unit: 5500,
})
Note: The minimum_capacity_unit 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.
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 add_target_groups instead of add_targets.
add_targets() will always return the Target Group it just created for you:
listener = nil # AWSCDK::ElasticLoadBalancingv2::NetworkListener
asg1 = nil # AWSCDK::Autoscaling::AutoScalingGroup
asg2 = nil # AWSCDK::Autoscaling::AutoScalingGroup
group = listener.add_targets("AppFleet", {
port: 443,
targets: [asg1],
})
group.add_target(asg2)
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 = nil # AWSCDK::EC2::VPC
# Target group with duration-based stickiness with load-balancer generated cookie
tg1 = AWSCDK::ElasticLoadBalancingv2::ApplicationTargetGroup.new(self, "TG1", {
target_type: AWSCDK::ElasticLoadBalancingv2::TargetType::INSTANCE,
port: 80,
stickiness_cookie_duration: AWSCDK::Duration.minutes(5),
vpc: vpc,
})
# Target group with application-based stickiness
tg2 = AWSCDK::ElasticLoadBalancingv2::ApplicationTargetGroup.new(self, "TG2", {
target_type: AWSCDK::ElasticLoadBalancingv2::TargetType::INSTANCE,
port: 80,
stickiness_cookie_duration: AWSCDK::Duration.minutes(5),
stickiness_cookie_name: "MyDeliciousCookie",
vpc: vpc,
})
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 = nil # AWSCDK::EC2::VPC
# Target group with slow start mode enabled
tg = AWSCDK::ElasticLoadBalancingv2::ApplicationTargetGroup.new(self, "TG", {
target_type: AWSCDK::ElasticLoadBalancingv2::TargetType::INSTANCE,
slow_start: AWSCDK::Duration.seconds(60),
port: 80,
vpc: vpc,
})
For more information see: https://docs.aws.amazon.com/elasticloadbalancing/latest/application/sticky-sessions.html#application-based-stickiness
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 = nil # AWSCDK::EC2::VPC
tg = AWSCDK::ElasticLoadBalancingv2::ApplicationTargetGroup.new(self, "TG", {
target_type: AWSCDK::ElasticLoadBalancingv2::TargetType::IP,
port: 50051,
protocol: AWSCDK::ElasticLoadBalancingv2::ApplicationProtocol::HTTP,
protocol_version: AWSCDK::ElasticLoadBalancingv2::ApplicationProtocolVersion::GRPC,
health_check: {
enabled: true,
healthy_grpc_codes: "0-99",
},
vpc: vpc,
})
You can use the weighted_random routing algorithms by setting the load_balancing_algorithm_type property.
When using this algorithm, Automatic Target Weights (ATW) anomaly mitigation can be used by setting enable_anomaly_mitigation 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 = nil # AWSCDK::EC2::VPC
tg = AWSCDK::ElasticLoadBalancingv2::ApplicationTargetGroup.new(self, "TargetGroup", {
vpc: vpc,
load_balancing_algorithm_type: AWSCDK::ElasticLoadBalancingv2::TargetGroupLoadBalancingAlgorithmType::WEIGHTED_RANDOM,
enable_anomaly_mitigation: true,
})
You can set cross-zone load balancing setting at the target group level by setting cross_zone property.
If not specified, it will use the load balancer's configuration.
For more information, see How Elastic Load Balancing works.
vpc = nil # AWSCDK::EC2::VPC
target_group = AWSCDK::ElasticLoadBalancingv2::ApplicationTargetGroup.new(self, "TargetGroup", {
vpc: vpc,
port: 80,
target_type: AWSCDK::ElasticLoadBalancingv2::TargetType::INSTANCE,
# Whether cross zone load balancing is enabled.
cross_zone_enabled: true,
})
You can set the IP address type for the target group by setting the ip_address_type property for both Application and Network target groups.
If you set the ip_address_type 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 = nil # AWSCDK::EC2::VPC
ipv4_application_target_group = AWSCDK::ElasticLoadBalancingv2::ApplicationTargetGroup.new(self, "IPv4ApplicationTargetGroup", {
vpc: vpc,
port: 80,
target_type: AWSCDK::ElasticLoadBalancingv2::TargetType::INSTANCE,
ip_address_type: AWSCDK::ElasticLoadBalancingv2::TargetGroupIPAddressType::IPV4,
})
ipv6_application_target_group = AWSCDK::ElasticLoadBalancingv2::ApplicationTargetGroup.new(self, "Ipv6ApplicationTargetGroup", {
vpc: vpc,
port: 80,
target_type: AWSCDK::ElasticLoadBalancingv2::TargetType::INSTANCE,
ip_address_type: AWSCDK::ElasticLoadBalancingv2::TargetGroupIPAddressType::IPV6,
})
ipv4_network_target_group = AWSCDK::ElasticLoadBalancingv2::NetworkTargetGroup.new(self, "IPv4NetworkTargetGroup", {
vpc: vpc,
port: 80,
target_type: AWSCDK::ElasticLoadBalancingv2::TargetType::INSTANCE,
ip_address_type: AWSCDK::ElasticLoadBalancingv2::TargetGroupIPAddressType::IPV4,
})
ipv6_network_target_group = AWSCDK::ElasticLoadBalancingv2::NetworkTargetGroup.new(self, "Ipv6NetworkTargetGroup", {
vpc: vpc,
port: 80,
target_type: AWSCDK::ElasticLoadBalancingv2::TargetType::INSTANCE,
ip_address_type: AWSCDK::ElasticLoadBalancingv2::TargetGroupIPAddressType::IPV6,
})
You can set target group health setting at target group level by setting target_group_health property.
For more information, see How Elastic Load Balancing works.
vpc = nil # AWSCDK::EC2::VPC
target_group = AWSCDK::ElasticLoadBalancingv2::ApplicationTargetGroup.new(self, "TargetGroup", {
vpc: vpc,
port: 80,
target_group_health: {
dns_minimum_healthy_target_count: 3,
dns_minimum_healthy_target_percentage: 70,
routing_minimum_healthy_target_count: 2,
routing_minimum_healthy_target_percentage: 50,
},
})
To use a Lambda Function as a target, use the integration class in the
aws-cdk-lib/aws-elasticloadbalancingv2-targets package:
require 'aws-cdk-lib'
lambda_function = nil # AWSCDK::Lambda::Function
lb = nil # AWSCDK::ElasticLoadBalancingv2::ApplicationLoadBalancer
listener = lb.add_listener("Listener", {port: 80})
listener.add_targets("Targets", {
targets: [AWSCDK::ElasticLoadBalancingv2Targets::LambdaTarget.new(lambda_function)],
# For Lambda Targets, you need to explicitly enable health checks if you
# want them.
health_check: {
enabled: true,
},
})
Only a single Lambda function can be added to a single listener rule.
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:
require 'aws-cdk-lib'
vpc = nil # AWSCDK::EC2::VPC
lambda_function = nil # AWSCDK::Lambda::Function
# Create a target group with multi-value headers enabled
target_group = AWSCDK::ElasticLoadBalancingv2::ApplicationTargetGroup.new(self, "LambdaTargetGroup", {
vpc: vpc,
targets: [AWSCDK::ElasticLoadBalancingv2Targets::LambdaTarget.new(lambda_function)],
# Enable multi-value headers
multi_value_headers_enabled: 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.
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:
require 'aws-cdk-lib'
vpc = nil # AWSCDK::EC2::VPC
task = AWSCDK::ECS::FargateTaskDefinition.new(self, "Task", {cpu: 256, memory_limit_mi_b: 512})
task.add_container("nginx", {
image: AWSCDK::ECS::ContainerImage.from_registry("public.ecr.aws/nginx/nginx:latest"),
port_mappings: [{container_port: 80}],
})
svc = AWSCDK::ECSPatterns::ApplicationLoadBalancedFargateService.new(self, "Service", {
vpc: vpc,
task_definition: task,
public_load_balancer: false,
})
nlb = AWSCDK::ElasticLoadBalancingv2::NetworkLoadBalancer.new(self, "Nlb", {
vpc: vpc,
cross_zone_enabled: true,
internet_facing: true,
})
listener = nlb.add_listener("listener", {port: 80})
listener.add_targets("Targets", {
targets: [AWSCDK::ElasticLoadBalancingv2Targets::ALBListenerTarget.new(svc.listener)],
port: 80,
})
AWSCDK::CfnOutput.new(self, "NlbEndpoint", {value: "http://#{nlb.load_balancer_dns_name}"})
Only the network load balancer is allowed to add the application load balancer as the target.
Health checks are configured upon creation of a target group:
listener = nil # AWSCDK::ElasticLoadBalancingv2::ApplicationListener
asg = nil # AWSCDK::Autoscaling::AutoScalingGroup
listener.add_targets("AppFleet", {
port: 8080,
targets: [asg],
health_check: {
path: "/ping",
interval: AWSCDK::Duration.minutes(1),
},
})
The health check can also be configured after creation by calling
configure_health_check() 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:
lb = nil # AWSCDK::ElasticLoadBalancingv2::ApplicationLoadBalancer
listener = nil # AWSCDK::ElasticLoadBalancingv2::ApplicationListener
asg = nil # AWSCDK::Autoscaling::AutoScalingGroup
listener.add_targets("AppFleet", {
port: 8080,
targets: [asg],
health_check: {
port: "8088",
},
})
asg.connections.allow_from(lb, AWSCDK::EC2::Port.tcp(8088))
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.
Constructs that want to be a load balancer target should implement
IApplicationLoadBalancerTarget and/or INetworkLoadBalancerTarget, and
provide an implementation for the function attach_to_xxx_target_group(), which can
call functions on the load balancer and should return metadata about the
load balancing target:
class MyTarget
include AWSCDK::ElasticLoadBalancingv2::IApplicationLoadBalancerTarget
def attach_to_application_target_group(target_group)
# If we need to add security group rules
# targetGroup.registerConnectable(...);
return {
target_type: AWSCDK::ElasticLoadBalancingv2::TargetType::IP,
target_json: {id: "1.2.3.4", port: 8080},
}
end
end
target_type should be one of Instance or Ip. If the target can be
directly added to the target group, target_json should contain the id of
the target (either instance ID or IP address depending on the type) and
optionally a port or availability_zone override.
Application load balancer targets can call register_connectable() 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 = nil # AWSCDK::Resource
target_group = nil # AWSCDK::ElasticLoadBalancingv2::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).add_dependency(target_group.load_balancer_attached)
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.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
load_balancer = AWSCDK::ElasticLoadBalancingv2::ApplicationLoadBalancer.from_lookup(self, "ALB", {
load_balancer_arn: "arn:aws:elasticloadbalancing:us-east-2:123456789012:loadbalancer/app/my-load-balancer/1234567890123456",
})
Look up an Application Load Balancer by tags
load_balancer = AWSCDK::ElasticLoadBalancingv2::ApplicationLoadBalancer.from_lookup(self, "ALB", {
load_balancer_tags: {
# Finds a load balancer matching all tags.
some: "tag",
someother: "tag",
},
})
You may look up a load balancer listener by the following criteria:
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
listener = AWSCDK::ElasticLoadBalancingv2::ApplicationListener.from_lookup(self, "ALBListener", {
load_balancer_arn: "arn:aws:elasticloadbalancing:us-east-2:123456789012:loadbalancer/app/my-load-balancer/1234567890123456",
listener_protocol: AWSCDK::ElasticLoadBalancingv2::ApplicationProtocol::HTTPS,
listener_port: 443,
})
Look up a Listener by associated Load Balancer Tag, Port, and Protocol
listener = AWSCDK::ElasticLoadBalancingv2::ApplicationListener.from_lookup(self, "ALBListener", {
load_balancer_tags: {
Cluster: "MyClusterName",
},
listener_protocol: AWSCDK::ElasticLoadBalancingv2::ApplicationProtocol::HTTPS,
listener_port: 443,
})
Look up a Network Listener by associated Load Balancer Tag, Port, and Protocol
listener = AWSCDK::ElasticLoadBalancingv2::NetworkListener.from_lookup(self, "ALBListener", {
load_balancer_tags: {
Cluster: "MyClusterName",
},
listener_protocol: AWSCDK::ElasticLoadBalancingv2::Protocol::TCP,
listener_port: 12345,
})
You may create metrics for Load Balancers and Target Groups through the metrics attribute:
Load Balancer:
alb = nil # AWSCDK::ElasticLoadBalancingv2::IApplicationLoadBalancer
alb_metrics = alb.metrics
metric_connection_count = alb_metrics.active_connection_count
Target Group:
target_group = nil # AWSCDK::ElasticLoadBalancingv2::IApplicationTargetGroup
target_group_metrics = target_group.metrics
metric_healthy_host_count = target_group_metrics.healthy_host_count
Metrics are also available to imported resources:
stack = nil # AWSCDK::Stack
target_group = AWSCDK::ElasticLoadBalancingv2::ApplicationTargetGroup.from_target_group_attributes(self, "MyTargetGroup", {
target_group_arn: AWSCDK::Fn.import_value("TargetGroupArn"),
load_balancer_arns: AWSCDK::Fn.import_value("LoadBalancerArn"),
})
target_group_metrics = target_group.metrics
Notice that TargetGroups must be imported by supplying the Load Balancer too, otherwise accessing the metrics will
throw an error:
stack = nil # AWSCDK::Stack
target_group = AWSCDK::ElasticLoadBalancingv2::ApplicationTargetGroup.from_target_group_attributes(self, "MyTargetGroup", {
target_group_arn: AWSCDK::Fn.import_value("TargetGroupArn"),
})
target_group_metrics = target_group.metrics
By default, the add_target_groups() 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 add_target_groups() the recommendation
is to set the removeRuleSuffixFromLogicalId: false property.
If you have ListenerRules deployed using the legacy behavior of add_target_groups(),
which you need to switch over to being managed by the add_action() method,
then you will need to enable the removeRuleSuffixFromLogicalId: true property in the add_action() 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.
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
require 'aws-cdk-lib'
certificate = nil # AWSCDK::CertificateManager::Certificate
lb = nil # AWSCDK::ElasticLoadBalancingv2::ApplicationLoadBalancer
bucket = nil # AWSCDK::S3::Bucket
trust_store = AWSCDK::ElasticLoadBalancingv2::TrustStore.new(self, "Store", {
bucket: bucket,
key: "rootCA_cert.pem",
})
lb.add_listener("Listener", {
port: 443,
protocol: AWSCDK::ElasticLoadBalancingv2::ApplicationProtocol::HTTPS,
certificates: [certificate],
# mTLS settings
mutual_authentication: {
advertise_trust_store_ca_names: true,
ignore_client_certificate_expiry: false,
mutual_authentication_mode: AWSCDK::ElasticLoadBalancingv2::MutualAuthenticationMode::VERIFY,
trust_store: trust_store,
},
default_action: AWSCDK::ElasticLoadBalancingv2::ListenerAction.fixed_response(200, {content_type: "text/plain", message_body: "Success mTLS"}),
})
Optionally, you can create a certificate revocation list for a trust store by creating an instance of TrustStoreRevocation.
trust_store = nil # AWSCDK::ElasticLoadBalancingv2::TrustStore
bucket = nil # AWSCDK::S3::Bucket
AWSCDK::ElasticLoadBalancingv2::TrustStoreRevocation.new(self, "Revocation", {
trust_store: trust_store,
revocation_contents: [
{
revocation_type: AWSCDK::ElasticLoadBalancingv2::RevocationType::CRL,
bucket: bucket,
key: "crl.pem",
},
],
})