Skip to main content

The CDK Construct Library for AWS::ElasticLoadBalancingV2

Project description

Amazon Elastic Load Balancing V2 Construct Library


Stability: Stable


The @aws-cdk/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 ec2 = require('@aws-cdk/aws-ec2');
import elbv2 = require('@aws-cdk/aws-elasticloadbalancingv2');
import autoscaling = require('@aws-cdk/aws-autoscaling');

// ...

const vpc = new ec2.Vpc(...);

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

// Add a listener and open up the load balancer's security group
// to the world. 'open' is the default, set this to 'false'
// and use `listener.connections` if you want to be selective
// about who can access the listener.
const listener = lb.addListener('Listener', {
    port: 80,
    open: true,
});

// Create an AutoScaling group and add it as a load balancing
// target to the listener.
const asg = new autoscaling.AutoScalingGroup(...);
listener.addTargets('ApplicationFleet', {
    port: 8080,
    targets: [asg]
});

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

Use the addFixedResponse() method to add fixed response rules on the listener:

listener.addFixedResponse('Fixed', {
    pathPattern: '/ok',
    contentType: elbv2.ContentType.TEXT_PLAIN,
    messageBody: 'OK',
    statusCode: '200'
});

Conditions

It's possible to route traffic to targets based on conditions in the incoming HTTP request. Path- and host-based conditions are supported. For example, the following will route requests to the indicated AutoScalingGroup only if the requested host in the request is example.com:

listener.addTargets('Example.Com Fleet', {
    priority: 10,
    hostHeader: 'example.com',
    port: 8080,
    targets: [asg]
});

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.

Defining a Network Load Balancer

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

import ec2 = require('@aws-cdk/aws-ec2');
import elbv2 = require('@aws-cdk/aws-elasticloadbalancingv2');
import autoscaling = require('@aws-cdk/aws-autoscaling');

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

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

// Add targets on a particular port.
listener.addTargets('AppFleet', {
    port: 443,
    targets: [asg]
});

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.

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:

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

group.addTarget(asg2);

Using Lambda Targets

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

import lambda = require('@aws-cdk/aws-lambda');
import elbv2 = require('@aws-cdk/aws-elasticloadbalancingv2');
import targets = require('@aws-cdk/aws-elasticloadbalancingv2-targets');

const lambdaFunction = new lambda.Function(...);
const loadBalancer = new elbv2.ApplicationLoadBalancer(...);

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

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

Configuring Health Checks

Health checks are configured upon creation of a target group:

listener.addTargets('AppFleet', {
    port: 8080,
    targets: [asg],
    healthCheck: {
        path: '/ping',
        interval: cdk.Duration.minutes(1),
    }
});

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

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

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

listener.connections.allowFrom(lb, ec2.Port.tcp(8088));

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 attachToApplicationTargetGroup(targetGroup: ApplicationTargetGroup): LoadBalancerTargetProps {
    targetGroup.registerConnectable(...);
    return {
        targetType: TargetType.Instance | TargetType.Ip
        targetJson: { id: ..., port: ... },
    };
}

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.loadBalancerDependency() as follows:

// Make sure that the listener has been created, and so the TargetGroup
// has been associated with the LoadBalancer, before 'resource' is created.
resourced.addDependency(targetGroup.loadBalancerDependency());

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

aws-cdk.aws-elasticloadbalancingv2-1.6.1.tar.gz (243.7 kB view details)

Uploaded Source

Built Distribution

File details

Details for the file aws-cdk.aws-elasticloadbalancingv2-1.6.1.tar.gz.

File metadata

  • Download URL: aws-cdk.aws-elasticloadbalancingv2-1.6.1.tar.gz
  • Upload date:
  • Size: 243.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.22.0 setuptools/39.0.1 requests-toolbelt/0.9.1 tqdm/4.35.0 CPython/3.6.5

File hashes

Hashes for aws-cdk.aws-elasticloadbalancingv2-1.6.1.tar.gz
Algorithm Hash digest
SHA256 4fe16719d391719088a8fc6d741b68af4fa7b393d2fef4158adff7aa3ed3ca28
MD5 bd1b5bdb8a3f432aa82beb37f01f4c6c
BLAKE2b-256 00ab59a5c0a4e2a370db59f2c24c4a788771f13dcb31bac737bbc2ec3d741db7

See more details on using hashes here.

File details

Details for the file aws_cdk.aws_elasticloadbalancingv2-1.6.1-py3-none-any.whl.

File metadata

File hashes

Hashes for aws_cdk.aws_elasticloadbalancingv2-1.6.1-py3-none-any.whl
Algorithm Hash digest
SHA256 680802899551e122cd5e27ac506716cab3934908a6466fa1a060860b25e6a2e1
MD5 52b5fe4087931f7096d1ea22eaaad6ff
BLAKE2b-256 cdc327202579d797113e28afcd4ff8e6d1a7495a559d9aa0d52cd17a18e05f52

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page