aws-cdk.aws-elasticloadbalancingv2


Nameaws-cdk.aws-elasticloadbalancingv2 JSON
Version 1.203.0 PyPI version JSON
download
home_pagehttps://github.com/aws/aws-cdk
SummaryThe CDK Construct Library for AWS::ElasticLoadBalancingV2
upload_time2023-05-31 23:02:21
maintainer
docs_urlNone
authorAmazon Web Services
requires_python~=3.7
licenseApache-2.0
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # 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
from aws_cdk.aws_autoscaling import AutoScalingGroup
# asg: 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.
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
# vpc: ec2.Vpc


security_group1 = ec2.SecurityGroup(self, "SecurityGroup1", vpc=vpc)
lb = elbv2.ApplicationLoadBalancer(self, "LB",
    vpc=vpc,
    internet_facing=True,
    security_group=security_group1
)

security_group2 = ec2.SecurityGroup(self, "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
# listener: elbv2.ApplicationListener
# asg: autoscaling.AutoScalingGroup


listener.add_targets("Example.Com Fleet",
    priority=10,
    conditions=[
        elbv2.ListenerCondition.host_headers(["example.com"]),
        elbv2.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.

A new listener can be added to the Load Balancer by calling `addListener()`.
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:

* `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
# listener: elbv2.ApplicationListener


listener.add_action("Fixed",
    priority=10,
    conditions=[
        elbv2.ListenerCondition.path_patterns(["/ok"])
    ],
    action=elbv2.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
# listener: elbv2.ApplicationListener
# my_target_group: elbv2.ApplicationTargetGroup


listener.add_action("DefaultAction",
    action=elbv2.ListenerAction.authenticate_oidc(
        authorization_endpoint="https://example.com/openid",
        # Other OIDC properties here
        client_id="...",
        client_secret=SecretValue.secrets_manager("..."),
        issuer="...",
        token_endpoint="...",
        user_info_endpoint="...",

        # Next
        next=elbv2.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
# lb: elbv2.ApplicationLoadBalancer


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.

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.

## Defining a Network Load Balancer

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

```python
# vpc: ec2.Vpc
# asg: autoscaling.AutoScalingGroup


# 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
# listener: elbv2.NetworkListener
# asg1: autoscaling.AutoScalingGroup
# asg2: autoscaling.AutoScalingGroup


group = listener.add_targets("AppFleet",
    port=443,
    targets=[asg1]
)

group.add_target(asg2)
```

### Sticky sessions for your Application Load Balancer

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.

```python
# vpc: ec2.Vpc


# Target group with duration-based stickiness with load-balancer generated cookie
tg1 = elbv2.ApplicationTargetGroup(self, "TG1",
    target_type=elbv2.TargetType.INSTANCE,
    port=80,
    stickiness_cookie_duration=Duration.minutes(5),
    vpc=vpc
)

# Target group with application-based stickiness
tg2 = elbv2.ApplicationTargetGroup(self, "TG2",
    target_type=elbv2.TargetType.INSTANCE,
    port=80,
    stickiness_cookie_duration=Duration.minutes(5),
    stickiness_cookie_name="MyDeliciousCookie",
    vpc=vpc
)
```

For more information see: https://docs.aws.amazon.com/elasticloadbalancing/latest/application/sticky-sessions.html#application-based-stickiness

### Setting the target group protocol version

By default, Application Load Balancers send requests to targets using HTTP/1.1. You can use the [protocol version](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-target-groups.html#target-group-protocol-version) to send requests to targets using HTTP/2 or gRPC.

```python
# vpc: ec2.Vpc


tg = elbv2.ApplicationTargetGroup(self, "TG",
    target_type=elbv2.TargetType.IP,
    port=50051,
    protocol=elbv2.ApplicationProtocol.HTTP,
    protocol_version=elbv2.ApplicationProtocolVersion.GRPC,
    health_check=elbv2.HealthCheck(
        enabled=True,
        healthy_grpc_codes="0-99"
    ),
    vpc=vpc
)
```

## Using Lambda Targets

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

```python
import aws_cdk.aws_lambda as lambda_
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=elbv2.HealthCheck(
        enabled=True
    )
)
```

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

## Using Application Load Balancer Targets

To use a single application load balancer as a target for the network load balancer, use the integration class in the
`@aws-cdk/aws-elasticloadbalancingv2-targets` package:

```python
import aws_cdk.aws_elasticloadbalancingv2_targets as targets
import aws_cdk.aws_ecs as ecs
import aws_cdk.aws_ecs_patterns as patterns

# vpc: ec2.Vpc


task = ecs.FargateTaskDefinition(self, "Task", cpu=256, memory_limit_mi_b=512)
task.add_container("nginx",
    image=ecs.ContainerImage.from_registry("public.ecr.aws/nginx/nginx:latest"),
    port_mappings=[ecs.PortMapping(container_port=80)]
)

svc = patterns.ApplicationLoadBalancedFargateService(self, "Service",
    vpc=vpc,
    task_definition=task,
    public_load_balancer=False
)

nlb = elbv2.NetworkLoadBalancer(self, "Nlb",
    vpc=vpc,
    cross_zone_enabled=True,
    internet_facing=True
)

listener = nlb.add_listener("listener", port=80)

listener.add_targets("Targets",
    targets=[targets.AlbTarget(svc.load_balancer, 80)],
    port=80
)

CfnOutput(self, "NlbEndpoint", value=f"http://{nlb.loadBalancerDnsName}")
```

Only the network load balancer is allowed to add the application load balancer as the target.

## Configuring Health Checks

Health checks are configured upon creation of a target group:

```python
# listener: elbv2.ApplicationListener
# asg: autoscaling.AutoScalingGroup


listener.add_targets("AppFleet",
    port=8080,
    targets=[asg],
    health_check=elbv2.HealthCheck(
        path="/ping",
        interval=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
# lb: elbv2.ApplicationLoadBalancer
# listener: elbv2.ApplicationListener
# asg: autoscaling.AutoScalingGroup


listener.add_targets("AppFleet",
    port=8080,
    targets=[asg],
    health_check=elbv2.HealthCheck(
        port="8088"
    )
)

asg.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
class MyTarget(elbv2.IApplicationLoadBalancerTarget):
    def attach_to_application_target_group(self, target_group):
        # If we need to add security group rules
        # targetGroup.registerConnectable(...);
        return elbv2.LoadBalancerTargetProps(
            target_type=elbv2.TargetType.IP,
            target_json={"id": "1.2.3.4", "port": 8080}
        )
```

`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.loadBalancerAttached` as follows:

```python
# resource: Resource
# target_group: elbv2.ApplicationTargetGroup


# Make sure that the listener has been created, and so the TargetGroup
# has been associated with the LoadBalancer, before 'resource' is created.

Node.of(resource).add_dependency(target_group.load_balancer_attached)
```

## Looking up Load Balancers and Listeners

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.

### Load Balancer lookup options

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**

```python
load_balancer = elbv2.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**

```python
load_balancer = elbv2.ApplicationLoadBalancer.from_lookup(self, "ALB",
    load_balancer_tags={
        # Finds a load balancer matching all tags.
        "some": "tag",
        "someother": "tag"
    }
)
```

## Load Balancer Listener lookup options

You may look up a load balancer listener by the following criteria:

* Associated load balancer ARN
* Associated load balancer tags
* Listener ARN
* Listener port
* Listener protocol

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**

```python
listener = elbv2.ApplicationListener.from_lookup(self, "ALBListener",
    load_balancer_arn="arn:aws:elasticloadbalancing:us-east-2:123456789012:loadbalancer/app/my-load-balancer/1234567890123456",
    listener_protocol=elbv2.ApplicationProtocol.HTTPS,
    listener_port=443
)
```

**Look up a Listener by associated Load Balancer Tag, Port, and Protocol**

```python
listener = elbv2.ApplicationListener.from_lookup(self, "ALBListener",
    load_balancer_tags={
        "Cluster": "MyClusterName"
    },
    listener_protocol=elbv2.ApplicationProtocol.HTTPS,
    listener_port=443
)
```

**Look up a Network Listener by associated Load Balancer Tag, Port, and Protocol**

```python
listener = elbv2.NetworkListener.from_lookup(self, "ALBListener",
    load_balancer_tags={
        "Cluster": "MyClusterName"
    },
    listener_protocol=elbv2.Protocol.TCP,
    listener_port=12345
)
```



            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/aws/aws-cdk",
    "name": "aws-cdk.aws-elasticloadbalancingv2",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "~=3.7",
    "maintainer_email": "",
    "keywords": "",
    "author": "Amazon Web Services",
    "author_email": "",
    "download_url": "https://files.pythonhosted.org/packages/5c/fc/1aaa660d2d36ed488cb553684a063dc094c61a5b46ad399b8f85d1c7adb2/aws-cdk.aws-elasticloadbalancingv2-1.203.0.tar.gz",
    "platform": null,
    "description": "# Amazon Elastic Load Balancing V2 Construct Library\n\n<!--BEGIN STABILITY BANNER-->---\n\n\n![cfn-resources: Stable](https://img.shields.io/badge/cfn--resources-stable-success.svg?style=for-the-badge)\n\n![cdk-constructs: Stable](https://img.shields.io/badge/cdk--constructs-stable-success.svg?style=for-the-badge)\n\n---\n<!--END STABILITY BANNER-->\n\nThe `@aws-cdk/aws-elasticloadbalancingv2` package provides constructs for\nconfiguring application and network load balancers.\n\nFor more information, see the AWS documentation for\n[Application Load Balancers](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/introduction.html)\nand [Network Load Balancers](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/introduction.html).\n\n## Defining an Application Load Balancer\n\nYou define an application load balancer by creating an instance of\n`ApplicationLoadBalancer`, adding a Listener to the load balancer\nand adding Targets to the Listener:\n\n```python\nfrom aws_cdk.aws_autoscaling import AutoScalingGroup\n# asg: AutoScalingGroup\n\n# vpc: ec2.Vpc\n\n\n# Create the load balancer in a VPC. 'internetFacing' is 'false'\n# by default, which creates an internal load balancer.\nlb = elbv2.ApplicationLoadBalancer(self, \"LB\",\n    vpc=vpc,\n    internet_facing=True\n)\n\n# Add a listener and open up the load balancer's security group\n# to the world.\nlistener = lb.add_listener(\"Listener\",\n    port=80,\n\n    # 'open: true' is the default, you can leave it out if you want. Set it\n    # to 'false' and use `listener.connections` if you want to be selective\n    # about who can access the load balancer.\n    open=True\n)\n\n# Create an AutoScaling group and add it as a load balancing\n# target to the listener.\nlistener.add_targets(\"ApplicationFleet\",\n    port=8080,\n    targets=[asg]\n)\n```\n\nThe security groups of the load balancer and the target are automatically\nupdated to allow the network traffic.\n\nOne (or more) security groups can be associated with the load balancer;\nif a security group isn't provided, one will be automatically created.\n\n```python\n# vpc: ec2.Vpc\n\n\nsecurity_group1 = ec2.SecurityGroup(self, \"SecurityGroup1\", vpc=vpc)\nlb = elbv2.ApplicationLoadBalancer(self, \"LB\",\n    vpc=vpc,\n    internet_facing=True,\n    security_group=security_group1\n)\n\nsecurity_group2 = ec2.SecurityGroup(self, \"SecurityGroup2\", vpc=vpc)\nlb.add_security_group(security_group2)\n```\n\n### Conditions\n\nIt's possible to route traffic to targets based on conditions in the incoming\nHTTP request. For example, the following will route requests to the indicated\nAutoScalingGroup only if the requested host in the request is either for\n`example.com/ok` or `example.com/path`:\n\n```python\n# listener: elbv2.ApplicationListener\n# asg: autoscaling.AutoScalingGroup\n\n\nlistener.add_targets(\"Example.Com Fleet\",\n    priority=10,\n    conditions=[\n        elbv2.ListenerCondition.host_headers([\"example.com\"]),\n        elbv2.ListenerCondition.path_patterns([\"/ok\", \"/path\"])\n    ],\n    port=8080,\n    targets=[asg]\n)\n```\n\nA target with a condition contains either `pathPatterns` or `hostHeader`, or\nboth. If both are specified, both conditions must be met for the requests to\nbe routed to the given target. `priority` is a required field when you add\ntargets with conditions. The lowest number wins.\n\nEvery listener must have at least one target without conditions, which is\nwhere all requests that didn't match any of the conditions will be sent.\n\n### Convenience methods and more complex Actions\n\nRouting traffic from a Load Balancer to a Target involves the following steps:\n\n* Create a Target Group, register the Target into the Target Group\n* Add an Action to the Listener which forwards traffic to the Target Group.\n\nA new listener can be added to the Load Balancer by calling `addListener()`.\nListeners that have been added to the load balancer can be listed using the\n`listeners` property.  Note that the `listeners` property will throw an Error\nfor imported or looked up Load Balancers.\n\nVarious methods on the `Listener` take care of this work for you to a greater\nor lesser extent:\n\n* `addTargets()` performs both steps: automatically creates a Target Group and the\n  required Action.\n* `addTargetGroups()` gives you more control: you create the Target Group (or\n  Target Groups) yourself and the method creates Action that routes traffic to\n  the Target Groups.\n* `addAction()` gives you full control: you supply the Action and wire it up\n  to the Target Groups yourself (or access one of the other ELB routing features).\n\nUsing `addAction()` gives you access to some of the features of an Elastic Load\nBalancer that the other two convenience methods don't:\n\n* **Routing stickiness**: use `ListenerAction.forward()` and supply a\n  `stickinessDuration` to make sure requests are routed to the same target group\n  for a given duration.\n* **Weighted Target Groups**: use `ListenerAction.weightedForward()`\n  to give different weights to different target groups.\n* **Fixed Responses**: use `ListenerAction.fixedResponse()` to serve\n  a static response (ALB only).\n* **Redirects**: use `ListenerAction.redirect()` to serve an HTTP\n  redirect response (ALB only).\n* **Authentication**: use `ListenerAction.authenticateOidc()` to\n  perform OpenID authentication before serving a request (see the\n  `@aws-cdk/aws-elasticloadbalancingv2-actions` package for direct authentication\n  integration with Cognito) (ALB only).\n\nHere's an example of serving a fixed response at the `/ok` URL:\n\n```python\n# listener: elbv2.ApplicationListener\n\n\nlistener.add_action(\"Fixed\",\n    priority=10,\n    conditions=[\n        elbv2.ListenerCondition.path_patterns([\"/ok\"])\n    ],\n    action=elbv2.ListenerAction.fixed_response(200,\n        content_type=elbv2.ContentType.TEXT_PLAIN,\n        message_body=\"OK\"\n    )\n)\n```\n\nHere's an example of using OIDC authentication before forwarding to a TargetGroup:\n\n```python\n# listener: elbv2.ApplicationListener\n# my_target_group: elbv2.ApplicationTargetGroup\n\n\nlistener.add_action(\"DefaultAction\",\n    action=elbv2.ListenerAction.authenticate_oidc(\n        authorization_endpoint=\"https://example.com/openid\",\n        # Other OIDC properties here\n        client_id=\"...\",\n        client_secret=SecretValue.secrets_manager(\"...\"),\n        issuer=\"...\",\n        token_endpoint=\"...\",\n        user_info_endpoint=\"...\",\n\n        # Next\n        next=elbv2.ListenerAction.forward([my_target_group])\n    )\n)\n```\n\nIf you just want to redirect all incoming traffic on one port to another port, you can use the following code:\n\n```python\n# lb: elbv2.ApplicationLoadBalancer\n\n\nlb.add_redirect(\n    source_protocol=elbv2.ApplicationProtocol.HTTPS,\n    source_port=8443,\n    target_protocol=elbv2.ApplicationProtocol.HTTP,\n    target_port=8080\n)\n```\n\nIf you do not provide any options for this method, it redirects HTTP port 80 to HTTPS port 443.\n\nBy default all ingress traffic will be allowed on the source port. If you want to be more selective with your\ningress rules then set `open: false` and use the listener's `connections` object to selectively grant access to the listener.\n\n## Defining a Network Load Balancer\n\nNetwork Load Balancers are defined in a similar way to Application Load\nBalancers:\n\n```python\n# vpc: ec2.Vpc\n# asg: autoscaling.AutoScalingGroup\n\n\n# Create the load balancer in a VPC. 'internetFacing' is 'false'\n# by default, which creates an internal load balancer.\nlb = elbv2.NetworkLoadBalancer(self, \"LB\",\n    vpc=vpc,\n    internet_facing=True\n)\n\n# Add a listener on a particular port.\nlistener = lb.add_listener(\"Listener\",\n    port=443\n)\n\n# Add targets on a particular port.\nlistener.add_targets(\"AppFleet\",\n    port=443,\n    targets=[asg]\n)\n```\n\nOne thing to keep in mind is that network load balancers do not have security\ngroups, and no automatic security group configuration is done for you. You will\nhave to configure the security groups of the target yourself to allow traffic by\nclients and/or load balancer instances, depending on your target types.  See\n[Target Groups for your Network Load\nBalancers](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-target-groups.html)\nand [Register targets with your Target\nGroup](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/target-group-register-targets.html)\nfor more information.\n\n## Targets and Target Groups\n\nApplication and Network Load Balancers organize load balancing targets in Target\nGroups. If you add your balancing targets (such as AutoScalingGroups, ECS\nservices or individual instances) to your listener directly, the appropriate\n`TargetGroup` will be automatically created for you.\n\nIf you need more control over the Target Groups created, create an instance of\n`ApplicationTargetGroup` or `NetworkTargetGroup`, add the members you desire,\nand add it to the listener by calling `addTargetGroups` instead of `addTargets`.\n\n`addTargets()` will always return the Target Group it just created for you:\n\n```python\n# listener: elbv2.NetworkListener\n# asg1: autoscaling.AutoScalingGroup\n# asg2: autoscaling.AutoScalingGroup\n\n\ngroup = listener.add_targets(\"AppFleet\",\n    port=443,\n    targets=[asg1]\n)\n\ngroup.add_target(asg2)\n```\n\n### Sticky sessions for your Application Load Balancer\n\nBy 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.\n\nApplication 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.\n\n```python\n# vpc: ec2.Vpc\n\n\n# Target group with duration-based stickiness with load-balancer generated cookie\ntg1 = elbv2.ApplicationTargetGroup(self, \"TG1\",\n    target_type=elbv2.TargetType.INSTANCE,\n    port=80,\n    stickiness_cookie_duration=Duration.minutes(5),\n    vpc=vpc\n)\n\n# Target group with application-based stickiness\ntg2 = elbv2.ApplicationTargetGroup(self, \"TG2\",\n    target_type=elbv2.TargetType.INSTANCE,\n    port=80,\n    stickiness_cookie_duration=Duration.minutes(5),\n    stickiness_cookie_name=\"MyDeliciousCookie\",\n    vpc=vpc\n)\n```\n\nFor more information see: https://docs.aws.amazon.com/elasticloadbalancing/latest/application/sticky-sessions.html#application-based-stickiness\n\n### Setting the target group protocol version\n\nBy default, Application Load Balancers send requests to targets using HTTP/1.1. You can use the [protocol version](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-target-groups.html#target-group-protocol-version) to send requests to targets using HTTP/2 or gRPC.\n\n```python\n# vpc: ec2.Vpc\n\n\ntg = elbv2.ApplicationTargetGroup(self, \"TG\",\n    target_type=elbv2.TargetType.IP,\n    port=50051,\n    protocol=elbv2.ApplicationProtocol.HTTP,\n    protocol_version=elbv2.ApplicationProtocolVersion.GRPC,\n    health_check=elbv2.HealthCheck(\n        enabled=True,\n        healthy_grpc_codes=\"0-99\"\n    ),\n    vpc=vpc\n)\n```\n\n## Using Lambda Targets\n\nTo use a Lambda Function as a target, use the integration class in the\n`@aws-cdk/aws-elasticloadbalancingv2-targets` package:\n\n```python\nimport aws_cdk.aws_lambda as lambda_\nimport aws_cdk.aws_elasticloadbalancingv2_targets as targets\n\n# lambda_function: lambda.Function\n# lb: elbv2.ApplicationLoadBalancer\n\n\nlistener = lb.add_listener(\"Listener\", port=80)\nlistener.add_targets(\"Targets\",\n    targets=[targets.LambdaTarget(lambda_function)],\n\n    # For Lambda Targets, you need to explicitly enable health checks if you\n    # want them.\n    health_check=elbv2.HealthCheck(\n        enabled=True\n    )\n)\n```\n\nOnly a single Lambda function can be added to a single listener rule.\n\n## Using Application Load Balancer Targets\n\nTo use a single application load balancer as a target for the network load balancer, use the integration class in the\n`@aws-cdk/aws-elasticloadbalancingv2-targets` package:\n\n```python\nimport aws_cdk.aws_elasticloadbalancingv2_targets as targets\nimport aws_cdk.aws_ecs as ecs\nimport aws_cdk.aws_ecs_patterns as patterns\n\n# vpc: ec2.Vpc\n\n\ntask = ecs.FargateTaskDefinition(self, \"Task\", cpu=256, memory_limit_mi_b=512)\ntask.add_container(\"nginx\",\n    image=ecs.ContainerImage.from_registry(\"public.ecr.aws/nginx/nginx:latest\"),\n    port_mappings=[ecs.PortMapping(container_port=80)]\n)\n\nsvc = patterns.ApplicationLoadBalancedFargateService(self, \"Service\",\n    vpc=vpc,\n    task_definition=task,\n    public_load_balancer=False\n)\n\nnlb = elbv2.NetworkLoadBalancer(self, \"Nlb\",\n    vpc=vpc,\n    cross_zone_enabled=True,\n    internet_facing=True\n)\n\nlistener = nlb.add_listener(\"listener\", port=80)\n\nlistener.add_targets(\"Targets\",\n    targets=[targets.AlbTarget(svc.load_balancer, 80)],\n    port=80\n)\n\nCfnOutput(self, \"NlbEndpoint\", value=f\"http://{nlb.loadBalancerDnsName}\")\n```\n\nOnly the network load balancer is allowed to add the application load balancer as the target.\n\n## Configuring Health Checks\n\nHealth checks are configured upon creation of a target group:\n\n```python\n# listener: elbv2.ApplicationListener\n# asg: autoscaling.AutoScalingGroup\n\n\nlistener.add_targets(\"AppFleet\",\n    port=8080,\n    targets=[asg],\n    health_check=elbv2.HealthCheck(\n        path=\"/ping\",\n        interval=Duration.minutes(1)\n    )\n)\n```\n\nThe health check can also be configured after creation by calling\n`configureHealthCheck()` on the created object.\n\nNo attempts are made to configure security groups for the port you're\nconfiguring a health check for, but if the health check is on the same port\nyou're routing traffic to, the security group already allows the traffic.\nIf not, you will have to configure the security groups appropriately:\n\n```python\n# lb: elbv2.ApplicationLoadBalancer\n# listener: elbv2.ApplicationListener\n# asg: autoscaling.AutoScalingGroup\n\n\nlistener.add_targets(\"AppFleet\",\n    port=8080,\n    targets=[asg],\n    health_check=elbv2.HealthCheck(\n        port=\"8088\"\n    )\n)\n\nasg.connections.allow_from(lb, ec2.Port.tcp(8088))\n```\n\n## Using a Load Balancer from a different Stack\n\nIf you want to put your Load Balancer and the Targets it is load balancing to in\ndifferent stacks, you may not be able to use the convenience methods\n`loadBalancer.addListener()` and `listener.addTargets()`.\n\nThe reason is that these methods will create resources in the same Stack as the\nobject they're called on, which may lead to cyclic references between stacks.\nInstead, you will have to create an `ApplicationListener` in the target stack,\nor an empty `TargetGroup` in the load balancer stack that you attach your\nservice to.\n\nFor an example of the alternatives while load balancing to an ECS service, see the\n[ecs/cross-stack-load-balancer\nexample](https://github.com/aws-samples/aws-cdk-examples/tree/master/typescript/ecs/cross-stack-load-balancer/).\n\n## Protocol for Load Balancer Targets\n\nConstructs that want to be a load balancer target should implement\n`IApplicationLoadBalancerTarget` and/or `INetworkLoadBalancerTarget`, and\nprovide an implementation for the function `attachToXxxTargetGroup()`, which can\ncall functions on the load balancer and should return metadata about the\nload balancing target:\n\n```python\nclass MyTarget(elbv2.IApplicationLoadBalancerTarget):\n    def attach_to_application_target_group(self, target_group):\n        # If we need to add security group rules\n        # targetGroup.registerConnectable(...);\n        return elbv2.LoadBalancerTargetProps(\n            target_type=elbv2.TargetType.IP,\n            target_json={\"id\": \"1.2.3.4\", \"port\": 8080}\n        )\n```\n\n`targetType` should be one of `Instance` or `Ip`. If the target can be\ndirectly added to the target group, `targetJson` should contain the `id` of\nthe target (either instance ID or IP address depending on the type) and\noptionally a `port` or `availabilityZone` override.\n\nApplication load balancer targets can call `registerConnectable()` on the\ntarget group to register themselves for addition to the load balancer's security\ngroup rules.\n\nIf your load balancer target requires that the TargetGroup has been\nassociated with a LoadBalancer before registration can happen (such as is the\ncase for ECS Services for example), take a resource dependency on\n`targetGroup.loadBalancerAttached` as follows:\n\n```python\n# resource: Resource\n# target_group: elbv2.ApplicationTargetGroup\n\n\n# Make sure that the listener has been created, and so the TargetGroup\n# has been associated with the LoadBalancer, before 'resource' is created.\n\nNode.of(resource).add_dependency(target_group.load_balancer_attached)\n```\n\n## Looking up Load Balancers and Listeners\n\nYou may look up load balancers and load balancer listeners by using one of the\nfollowing lookup methods:\n\n* `ApplicationLoadBalancer.fromlookup(options)` - Look up an application load\n  balancer.\n* `ApplicationListener.fromLookup(options)` - Look up an application load\n  balancer listener.\n* `NetworkLoadBalancer.fromLookup(options)` - Look up a network load balancer.\n* `NetworkListener.fromLookup(options)` - Look up a network load balancer\n  listener.\n\n### Load Balancer lookup options\n\nYou may look up a load balancer by ARN or by associated tags. When you look a\nload balancer up by ARN, that load balancer will be returned unless CDK detects\nthat the load balancer is of the wrong type. When you look up a load balancer by\ntags, CDK will return the load balancer matching all specified tags. If more\nthan one load balancer matches, CDK will throw an error requesting that you\nprovide more specific criteria.\n\n**Look up a Application Load Balancer by ARN**\n\n```python\nload_balancer = elbv2.ApplicationLoadBalancer.from_lookup(self, \"ALB\",\n    load_balancer_arn=\"arn:aws:elasticloadbalancing:us-east-2:123456789012:loadbalancer/app/my-load-balancer/1234567890123456\"\n)\n```\n\n**Look up an Application Load Balancer by tags**\n\n```python\nload_balancer = elbv2.ApplicationLoadBalancer.from_lookup(self, \"ALB\",\n    load_balancer_tags={\n        # Finds a load balancer matching all tags.\n        \"some\": \"tag\",\n        \"someother\": \"tag\"\n    }\n)\n```\n\n## Load Balancer Listener lookup options\n\nYou may look up a load balancer listener by the following criteria:\n\n* Associated load balancer ARN\n* Associated load balancer tags\n* Listener ARN\n* Listener port\n* Listener protocol\n\nThe lookup method will return the matching listener. If more than one listener\nmatches, CDK will throw an error requesting that you specify additional\ncriteria.\n\n**Look up a Listener by associated Load Balancer, Port, and Protocol**\n\n```python\nlistener = elbv2.ApplicationListener.from_lookup(self, \"ALBListener\",\n    load_balancer_arn=\"arn:aws:elasticloadbalancing:us-east-2:123456789012:loadbalancer/app/my-load-balancer/1234567890123456\",\n    listener_protocol=elbv2.ApplicationProtocol.HTTPS,\n    listener_port=443\n)\n```\n\n**Look up a Listener by associated Load Balancer Tag, Port, and Protocol**\n\n```python\nlistener = elbv2.ApplicationListener.from_lookup(self, \"ALBListener\",\n    load_balancer_tags={\n        \"Cluster\": \"MyClusterName\"\n    },\n    listener_protocol=elbv2.ApplicationProtocol.HTTPS,\n    listener_port=443\n)\n```\n\n**Look up a Network Listener by associated Load Balancer Tag, Port, and Protocol**\n\n```python\nlistener = elbv2.NetworkListener.from_lookup(self, \"ALBListener\",\n    load_balancer_tags={\n        \"Cluster\": \"MyClusterName\"\n    },\n    listener_protocol=elbv2.Protocol.TCP,\n    listener_port=12345\n)\n```\n\n\n",
    "bugtrack_url": null,
    "license": "Apache-2.0",
    "summary": "The CDK Construct Library for AWS::ElasticLoadBalancingV2",
    "version": "1.203.0",
    "project_urls": {
        "Homepage": "https://github.com/aws/aws-cdk",
        "Source": "https://github.com/aws/aws-cdk.git"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "76c8b40e893e70f775a75c9f0fe90338400d7e1d7f0ba858a25053ddb948c523",
                "md5": "a87bdacae610d275aedf21bbd3e8a0cf",
                "sha256": "1cec620d377138e03ee8b8747e377ba335e239fa95253242a1a750f24b064130"
            },
            "downloads": -1,
            "filename": "aws_cdk.aws_elasticloadbalancingv2-1.203.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "a87bdacae610d275aedf21bbd3e8a0cf",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "~=3.7",
            "size": 585495,
            "upload_time": "2023-05-31T22:54:50",
            "upload_time_iso_8601": "2023-05-31T22:54:50.309219Z",
            "url": "https://files.pythonhosted.org/packages/76/c8/b40e893e70f775a75c9f0fe90338400d7e1d7f0ba858a25053ddb948c523/aws_cdk.aws_elasticloadbalancingv2-1.203.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "5cfc1aaa660d2d36ed488cb553684a063dc094c61a5b46ad399b8f85d1c7adb2",
                "md5": "f3c4b863d0f981433f29503a31d613dc",
                "sha256": "886fb98e2e9970b7b0452823e2a4275db4611bc85e5ee7e7c8b17a43958f52b5"
            },
            "downloads": -1,
            "filename": "aws-cdk.aws-elasticloadbalancingv2-1.203.0.tar.gz",
            "has_sig": false,
            "md5_digest": "f3c4b863d0f981433f29503a31d613dc",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "~=3.7",
            "size": 585983,
            "upload_time": "2023-05-31T23:02:21",
            "upload_time_iso_8601": "2023-05-31T23:02:21.595466Z",
            "url": "https://files.pythonhosted.org/packages/5c/fc/1aaa660d2d36ed488cb553684a063dc094c61a5b46ad399b8f85d1c7adb2/aws-cdk.aws-elasticloadbalancingv2-1.203.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-05-31 23:02:21",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "aws",
    "github_project": "aws-cdk",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "aws-cdk.aws-elasticloadbalancingv2"
}
        
Elapsed time: 0.17246s