AWS CDK Elastic Load Balancing V2
The `aws-cdk-aws-elasticloadbalancingv2` library is the AWS Cloud Development Kit (CDK) Construct Library for AWS Elastic Load Balancing V2 (ALB and NLB). It allows developers to define and deploy load balancers using familiar programming languages. The current version is 1.204.0, and it follows the frequent release cadence of the broader AWS CDK project.
Common errors
-
AttributeError: module 'aws_cdk.aws_elasticloadbalancingv2' has no attribute 'ApplicationLoadBalancer'
cause Attempting to use a CDK v2 import pattern (e.g., `aws_cdk.aws_lb`) in a CDK v1 project, or incorrect import alias/name, or missing package installation.fixEnsure `aws-cdk-aws-elasticloadbalancingv2` is installed and `aws-cdk.core` is compatible. For CDK v1, use `from aws_cdk import aws_elasticloadbalancingv2 as elbv2`. If targeting CDK v2, the import should be `from aws_cdk import aws_lb as elbv2`. -
ValidationError: At least two subnets must be specified.
cause Load balancers require at least two subnets in different Availability Zones within the VPC for high availability. This error occurs if the provided VPC does not have sufficient subnets or if explicit `vpc_subnets` selection results in fewer than two.fixEnsure the `ec2.Vpc` object passed to the load balancer has at least two subnets, ideally across different AZs. If using `ec2.Vpc.from_lookup`, verify the looked-up VPC meets this requirement. When creating a new VPC, ensure `max_azs` is at least 2. -
No security groups were specified for the load balancer (when trying to access the ALB) or The load balancer does not have an internet-facing scheme. Accessing it via public DNS will fail.
cause ALBs require security groups to control network access. If none are provided, or if the load balancer is configured as internal (`internet_facing=False`) but accessed externally, these issues arise.fixProvide one or more `ec2.SecurityGroup` objects to the `security_groups` property of the `ApplicationLoadBalancer`. Ensure these security groups allow necessary inbound traffic (e.g., HTTP/80, HTTPS/443). Confirm `internet_facing` property matches intended access pattern.
Warnings
- breaking Major breaking changes occurred during migration from AWS CDK v1 to v2. Import paths, module names, and certain APIs for ELBv2 constructs (e.g., `aws_elasticloadbalancingv2` changed to `aws_lb`) have been updated.
- gotcha Failing to explicitly set `internet_facing=False` when an internal ALB/NLB is desired can accidentally expose services publicly or result in unexpected network behavior.
- gotcha Misconfigured target group health checks (e.g., wrong path, port, or status codes, or invalid security group rules) are a very common cause of targets not registering, appearing unhealthy, or failing to receive traffic.
Install
-
pip install aws-cdk-aws-elasticloadbalancingv2
Imports
- ApplicationLoadBalancer
from aws_cdk import aws_elasticloadbalancingv2 as elbv2
- NetworkLoadBalancer
from aws_cdk import aws_elasticloadbalancingv2 as elbv2
- ApplicationTargetGroup
from aws_cdk import aws_elasticloadbalancingv2 as elbv2
- Vpc
from aws_cdk.aws_ec2 import Vpc
from aws_cdk import aws_ec2 as ec2
Quickstart
import os
from aws_cdk import (
App, Stack,
aws_ec2 as ec2,
aws_elasticloadbalancingv2 as elbv2,
Environment
)
class MyAlbStack(Stack):
def __init__(self, scope: App, id: str, **kwargs):
super().__init__(scope, id, **kwargs)
# Look up an existing VPC or create a new one
# For simplicity, creating a minimal one for quickstart
vpc = ec2.Vpc(self, "MyAlbVpc",
max_azs=2,
nat_gateways=0 # Minimal cost
)
# Create an Application Load Balancer
alb = elbv2.ApplicationLoadBalancer(self, "MyAlb",
vpc=vpc,
internet_facing=True,
load_balancer_name="MyQuickstartALB"
)
# Add a listener for HTTP traffic on port 80
listener = alb.add_listener("MyHttpListener",
port=80,
open=True # Allow all inbound traffic for quickstart
)
# Add a default target group (e.g., an empty one for now)
# In a real app, you would add instances or IP targets here
listener.add_targets("MyTargetGroup",
port=80,
targets=[] # No targets initially
)
# Output the ALB DNS name
# CfnOutput(self, "AlbDnsName", value=alb.load_balancer_dns_name)
app = App()
MyAlbStack(app, "AlbQuickstartStack",
env=Environment(
account=os.environ.get("CDK_DEFAULT_ACCOUNT"),
region=os.environ.get("CDK_DEFAULT_REGION")
)
)
app.synth()