AWS CDK Elastic Load Balancing V2

1.204.0 · active · verified Fri Apr 17

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

Warnings

Install

Imports

Quickstart

This quickstart code defines a basic AWS CDK stack that creates an Application Load Balancer (ALB) within a new VPC. It configures the ALB to be internet-facing with an HTTP listener on port 80 and an empty default target group. This provides a minimal runnable example to demonstrate the core components of ELBv2 with CDK.

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()

view raw JSON →