Metadata-Version: 2.1
Name: aws-cdk.aws-elasticloadbalancingv2
Version: 1.66.0
Summary: The CDK Construct Library for AWS::ElasticLoadBalancingV2
Home-page: https://github.com/aws/aws-cdk
Author: Amazon Web Services
License: Apache-2.0
Project-URL: Source, https://github.com/aws/aws-cdk.git
Platform: UNKNOWN
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: JavaScript
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.6
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Typing :: Typed
Classifier: Development Status :: 5 - Production/Stable
Classifier: License :: OSI Approved
Classifier: Framework :: AWS CDK
Classifier: Framework :: AWS CDK :: 1
Requires-Python: >=3.6
Description-Content-Type: text/markdown
Requires-Dist: aws-cdk.aws-certificatemanager (==1.66.0)
Requires-Dist: aws-cdk.aws-cloudwatch (==1.66.0)
Requires-Dist: aws-cdk.aws-ec2 (==1.66.0)
Requires-Dist: aws-cdk.aws-iam (==1.66.0)
Requires-Dist: aws-cdk.aws-lambda (==1.66.0)
Requires-Dist: aws-cdk.aws-s3 (==1.66.0)
Requires-Dist: aws-cdk.core (==1.66.0)
Requires-Dist: aws-cdk.region-info (==1.66.0)
Requires-Dist: constructs (<4.0.0,>=3.0.4)
Requires-Dist: jsii (<2.0.0,>=1.13.0)
Requires-Dist: publication (>=0.0.3)

## Amazon Elastic Load Balancing V2 Construct Library

<!--BEGIN STABILITY BANNER-->---


![cfn-resources: Stable](https://img.shields.io/badge/cfn--resources-stable-success.svg?style=for-the-badge)

![cdk-constructs: Stable](https://img.shields.io/badge/cdk--constructs-stable-success.svg?style=for-the-badge)

---
<!--END STABILITY BANNER-->

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](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/introduction.html)
and [Network Load Balancers](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/introduction.html).

### 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:

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import aws_cdk.aws_ec2 as ec2
import aws_cdk.aws_elasticloadbalancingv2 as elbv2
from aws_cdk.aws_autoscaling import AutoScalingGroup

# ...

vpc = ec2.Vpc(...)

# Create the load balancer in a VPC. 'internetFacing' is 'false'
# by default, which creates an internal load balancer.
lb = elbv2.ApplicationLoadBalancer(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.
asg = AutoScalingGroup(...)
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.

One (or more) security groups can be associated with the load balancer;
if a security group isn't provided, one will be automatically created.

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
security_group1 = ec2.SecurityGroup(stack, "SecurityGroup1", vpc=vpc)
lb = elbv2.ApplicationLoadBalancer(self, "LB",
    vpc=vpc,
    internet_facing=True,
    security_group=security_group1
)

security_group2 = ec2.SecurityGroup(stack, "SecurityGroup2", vpc=vpc)
lb.add_security_group(security_group2)
```

#### 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`:

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
listener.add_targets("Example.Com Fleet",
    priority=10,
    conditions=[
        ListenerCondition.host_headers(["example.com"]),
        ListenerCondition.path_patterns(["/ok", "/path"])
    ],
    port=8080,
    targets=[asg]
)
```

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.

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 a
  `stickinessDuration` 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 the
  `@aws-cdk/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:

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
listener.add_action("Fixed",
    priority=10,
    conditions=[
        ListenerCondition.path_patterns(["/ok"])
    ],
    action=ListenerAction.fixed_response(200,
        content_type=elbv2.ContentType.TEXT_PLAIN,
        message_body="OK"
    )
)
```

Here's an example of using OIDC authentication before forwarding to a TargetGroup:

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
listener.add_action("DefaultAction",
    action=ListenerAction.authenticate_oidc(
        authorization_endpoint="https://example.com/openid",
        # Other OIDC properties here
        # ...
        next=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:

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
lb.add_redirect(
    source_protocol=elbv2.ApplicationProtocol.HTTPS,
    source_port=8443,
    target_protocol=elbv2.ApplicationProtocol.HTTP,
    target_port=8080
)
```

If you do not provide any options for this method, it redirects HTTP port 80 to HTTPS port 443.

### Defining a Network Load Balancer

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

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import aws_cdk.aws_ec2 as ec2
import aws_cdk.aws_elasticloadbalancingv2 as elbv2
import aws_cdk.aws_autoscaling as autoscaling

# Create the load balancer in a VPC. 'internetFacing' is 'false'
# by default, which creates an internal load balancer.
lb = elbv2.NetworkLoadBalancer(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]
)
```

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](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-target-groups.html)
and [Register targets with your Target
Group](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/target-group-register-targets.html)
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:

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
group = listener.add_targets("AppFleet",
    port=443,
    targets=[asg1]
)

group.add_target(asg2)
```

### Using Lambda Targets

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

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
import aws_cdk.aws_lambda as lambda_
import aws_cdk.aws_elasticloadbalancingv2 as elbv2
import aws_cdk.aws_elasticloadbalancingv2_targets as targets

lambda_function = lambda_.Function(...)
lb = elbv2.ApplicationLoadBalancer(...)

listener = lb.add_listener("Listener", port=80)
listener.add_targets("Targets",
    targets=[targets.LambdaTarget(lambda_function)],

    # For Lambda Targets, you need to explicitly enable health checks if you
    # want them.
    health_check=HealthCheck(
        enabled=True
    )
)
```

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:

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
listener.add_targets("AppFleet",
    port=8080,
    targets=[asg],
    health_check={
        "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:

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
listener.add_targets("AppFleet",
    port=8080,
    targets=[asg],
    health_check={
        "port": 8088
    }
)

listener.connections.allow_from(lb, ec2.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](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/cross-stack-load-balancer/).

### 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:

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
attach_to_application_target_group(target_group, ApplicationTargetGroup)LoadBalancerTargetProps
    target_group.register_connectable(...)return {
        "target_type": TargetType.Instance | TargetType.Ip,
        "target_json": {"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:

```python
# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
# Make sure that the listener has been created, and so the TargetGroup
# has been associated with the LoadBalancer, before 'resource' is created.
resourced.add_dependency(target_group.load_balancer_dependency())
```


