Skip to content
v2.273.0

ApplicationListener L2 construct ​

Define an ApplicationListener.

Example ​

ts
import { AutoScalingGroup } from 'aws-cdk-lib/aws-autoscaling';
declare const asg: AutoScalingGroup;
declare const vpc: 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.
const listener = lb.addListener('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.addTargets('ApplicationFleet', {
  port: 8080,
  targets: [asg]
});
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]
)
java
import software.amazon.awscdk.services.autoscaling.AutoScalingGroup;
AutoScalingGroup asg;
Vpc vpc;


// Create the load balancer in a VPC. 'internetFacing' is 'false'
// by default, which creates an internal load balancer.
ApplicationLoadBalancer lb = ApplicationLoadBalancer.Builder.create(this, "LB")
        .vpc(vpc)
        .internetFacing(true)
        .build();

// Add a listener and open up the load balancer's security group
// to the world.
ApplicationListener listener = lb.addListener("Listener", BaseApplicationListenerProps.builder()
        .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)
        .build());

// Create an AutoScaling group and add it as a load balancing
// target to the listener.
listener.addTargets("ApplicationFleet", AddApplicationTargetsProps.builder()
        .port(8080)
        .targets(List.of(asg))
        .build());
csharp
// Install: dotnet add package Amazon.CDK.Lib
using Amazon.CDK.AWS.AutoScaling;
AutoScalingGroup asg;
Vpc vpc;


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

// Add a listener and open up the load balancer's security group
// to the world.
var listener = lb.AddListener("Listener", new BaseApplicationListenerProps {
    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.AddTargets("ApplicationFleet", new AddApplicationTargetsProps {
    Port = 8080,
    Targets = new [] { asg }
});
go
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
import "github.com/aws/aws-cdk-go/awscdk"
var asg AutoScalingGroup
var vpc Vpc


// Create the load balancer in a VPC. 'internetFacing' is 'false'
// by default, which creates an internal load balancer.
lb := elbv2.NewApplicationLoadBalancer(this, jsii.String("LB"), &ApplicationLoadBalancerProps{
	Vpc: Vpc,
	InternetFacing: jsii.Boolean(true),
})

// Add a listener and open up the load balancer's security group
// to the world.
listener := lb.AddListener(jsii.String("Listener"), &BaseApplicationListenerProps{
	Port: jsii.Number(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: jsii.Boolean(true),
})

// Create an AutoScaling group and add it as a load balancing
// target to the listener.
listener.AddTargets(jsii.String("ApplicationFleet"), &AddApplicationTargetsProps{
	Port: jsii.Number(8080),
	Targets: []IApplicationLoadBalancerTarget{
		asg,
	},
})

Initializer ​

ts
new ApplicationListener(scope: Construct, id: string, props: ApplicationListenerProps)
python
ApplicationListener(scope: Construct, id: str, props: ApplicationListenerProps)
java
new ApplicationListener(Construct scope, String id, ApplicationListenerProps props)
csharp
new ApplicationListener(Construct scope, string id, ApplicationListenerProps props)
go
NewApplicationListener(Scope Construct, Id *string, Props ApplicationListenerProps)

Construct Props ​

certificatesIListenerCertificate[]certificatestyping.List[IListenerCertificate]certificatesList<IListenerCertificate>CertificatesIListenerCertificate[]Certificates*[]IListenerCertificate= No certificates.#
Certificate list of ACM cert ARNs.

You must provide exactly one certificate if the listener protocol is HTTPS or TLS.

defaultActionListenerActiondefault_actionListenerActiondefaultActionListenerActionDefaultActionListenerActionDefaultActionListenerAction= None.#
Default action to take for requests to this listener.
notes

This allows full control of the default action of the load balancer, including Action chaining, fixed responses and redirect responses.

See the ListenerAction class for all options.

Cannot be specified together with defaultTargetGroups.

defaultTargetGroupsIApplicationTargetGroup[]default_target_groupstyping.List[IApplicationTargetGroup]defaultTargetGroupsList<IApplicationTargetGroup>DefaultTargetGroupsIApplicationTargetGroup[]DefaultTargetGroups*[]IApplicationTargetGroup= None.#
Default target groups to load balance to.

All target groups will be load balanced to with equal weight and without stickiness. For a more complex configuration than that, use either defaultAction or addAction().

Cannot be specified together with defaultAction.

The load balancer to attach this listener to.
mutualAuthenticationMutualAuthenticationmutual_authenticationMutualAuthenticationmutualAuthenticationMutualAuthenticationMutualAuthenticationMutualAuthenticationMutualAuthenticationMutualAuthentication= No mutual authentication configu…#
The mutual authentication configuration information.
default

Default: No mutual authentication configuration

openbooleanopenboolopenBooleanOpenboolOpen*bool= true#
Allow anyone to connect to the load balancer on the listener port.
notes

If this is specified, the load balancer will be opened up to anyone who can reach it. For internal load balancers this is anyone in the same VPC. For public load balancers, this is anyone on the internet.

If you want to be more selective about who can access this load balancer, set this to false and use the listener's connections object to selectively grant access to the load balancer on the listener port.

portnumberportint | floatportNumberPortdoublePort*float64= Determined from protocol if know…#
The port on which the listener listens for requests.
default

Default: Determined from protocol if known.

protocolApplicationProtocolprotocolApplicationProtocolprotocolApplicationProtocolProtocolApplicationProtocolProtocolApplicationProtocol= Determined from port if known.#
The protocol to use.
sslPolicySslPolicyssl_policySslPolicysslPolicySslPolicySslPolicySslPolicySslPolicySslPolicy= The current predefined security …#
The security policy that defines which ciphers and protocols are supported.
default

Default: The current predefined security policy.

Properties ​

connectionsConnectionsconnectionsConnectionsconnectionsConnectionsConnectionsConnectionsConnectionsConnectionsrequired#
Manage connections to this ApplicationListener.
The environment this resource belongs to.
notes

For resources that are created and managed in a Stack (those created by creating new class instances like new Role(), new Bucket(), etc.), this is always the same as the environment of the stack they belong to.

For referenced resources (those obtained from referencing methods like Role.fromRoleArn(), Bucket.fromBucketName(), etc.), they might be different than the stack they were imported into.

isApplicationListenerbooleanis_application_listenerboolisApplicationListenerBooleanIsApplicationListenerboolIsApplicationListener*boolrequired#
Indicates that this is an ALB listener.

Will always return true, but is necessary to prevent accidental structural equality in TypeScript.

listenerArnstringlistener_arnstrlistenerArnStringListenerArnstringListenerArn*stringrequired#
ARN of the listener.
listenerRefListenerReferencelistener_refListenerReferencelistenerRefListenerReferenceListenerRefListenerReferenceListenerRefListenerReferencerequired#
A reference to this listener.
Load balancer this listener is associated with.
nodeNodenodeNodenodeNodeNodeNodeNodeNoderequired#
The tree node.
portnumberportint | floatportNumberPortdoublePort*float64required#
The port of the listener.
PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#
Uniquely identifies this class.
Listener protocol for this listener.
stackStackstackStackstackStackStackStackStackStackrequired#
The stack in which this resource is defined.

Methods ​

addAction(id: string, props: AddApplicationActionProps): voiddef add_action(self, id: str, props: AddApplicationActionProps) -> Nonepublic void addAction(String id, AddApplicationActionProps props)public void AddAction(string id, AddApplicationActionProps props)func AddAction(Id *string, Props AddApplicationActionProps)#
Perform the given default action on incoming requests.
notes

This allows full control of the default action of the load balancer, including Action chaining, fixed responses and redirect responses. See the ListenerAction class for all options.

It's possible to add routing conditions to the Action added in this way. At least one Action must be added without conditions (which becomes the default Action).

addCertificates(id: string, certificates: IListenerCertificate[]): voiddef add_certificates(self, id: str, certificates: typing.List[IListenerCertificate]) -> Nonepublic void addCertificates(String id, List<IListenerCertificate> certificates)public void AddCertificates(string id, IListenerCertificate[] certificates)func AddCertificates(Id *string, Certificates *[]IListenerCertificate)#
Add one or more certificates to this listener.

After the first certificate, this creates ApplicationListenerCertificates resources since cloudformation requires the certificates array on the listener resource to have a length of 1.

addTargetGroups(id: string, props: AddApplicationTargetGroupsProps): voiddef add_target_groups(self, id: str, props: AddApplicationTargetGroupsProps) -> Nonepublic void addTargetGroups(String id, AddApplicationTargetGroupsProps props)public void AddTargetGroups(string id, AddApplicationTargetGroupsProps props)func AddTargetGroups(Id *string, Props AddApplicationTargetGroupsProps)#
Load balance incoming requests to the given target groups.
notes

All target groups will be load balanced to with equal weight and without stickiness. For a more complex configuration than that, use addAction().

It's possible to add routing conditions to the TargetGroups added in this way. At least one TargetGroup must be added without conditions (which will become the default Action for this listener).

addTargets(id: string, props: AddApplicationTargetsProps): ApplicationTargetGroupdef add_targets(self, id: str, props: AddApplicationTargetsProps) -> ApplicationTargetGrouppublic ApplicationTargetGroup addTargets(String id, AddApplicationTargetsProps props)public ApplicationTargetGroup AddTargets(string id, AddApplicationTargetsProps props)func AddTargets(Id *string, Props AddApplicationTargetsProps) ApplicationTargetGroup#
Load balance incoming requests to the given load balancing targets.
notes · returns

This method implicitly creates an ApplicationTargetGroup for the targets involved, and a 'forward' action to route traffic to the given TargetGroup.

If you want more control over the precise setup, create the TargetGroup and use addAction yourself.

It's possible to add conditions to the targets added in this way. At least one set of targets must be added without conditions.

Returns: The newly created target group

applyCrossStackReferenceStrength(strength: ReferenceStrength): voiddef apply_cross_stack_reference_strength(self, strength: ReferenceStrength) -> Nonepublic void applyCrossStackReferenceStrength(ReferenceStrength strength)public void ApplyCrossStackReferenceStrength(ReferenceStrength strength)func ApplyCrossStackReferenceStrength(Strength ReferenceStrength)#
Override the cross-stack reference strength for this resource.
notes · 1 parameter

When set, any cross-stack reference to this resource will use the specified mechanism instead of the global default determined by the @aws-cdk/core:defaultCrossStackReferences context key. This is useful for selectively weakening specific references to avoid the "deadly embrace" problem without changing the app-wide default.

Parameters

  • strengthstrengthstrengthstrengthStrength — - The reference strength to use for this resource.
applyRemovalPolicy(policy: RemovalPolicy): voiddef apply_removal_policy(self, policy: RemovalPolicy) -> Nonepublic void applyRemovalPolicy(RemovalPolicy policy)public void ApplyRemovalPolicy(RemovalPolicy policy)func ApplyRemovalPolicy(Policy RemovalPolicy)#
Apply the given removal policy to this resource.
notes

The Removal Policy controls what happens to this resource when it stops being managed by CloudFormation, either because you've removed it from the CDK application or because you've made a change that requires the resource to be replaced.

The resource can be deleted (RemovalPolicy.DESTROY), or left in your AWS account for data recovery and cleanup later (RemovalPolicy.RETAIN).

fromApplicationListenerAttributes(scope: Construct, id: string, attrs: ApplicationListenerAttributes): IApplicationListener@staticmethod def from_application_listener_attributes(scope: Construct, id: str, attrs: ApplicationListenerAttributes) -> IApplicationListenerpublic static IApplicationListener fromApplicationListenerAttributes(Construct scope, String id, ApplicationListenerAttributes attrs)public static IApplicationListener FromApplicationListenerAttributes(Construct scope, string id, ApplicationListenerAttributes attrs)func FromApplicationListenerAttributes(Scope Construct, Id *string, Attrs ApplicationListenerAttributes) IApplicationListenerstatic#
Import an existing listener.
fromLookup(scope: Construct, id: string, options: ApplicationListenerLookupOptions): IApplicationListener@staticmethod def from_lookup(scope: Construct, id: str, options: ApplicationListenerLookupOptions) -> IApplicationListenerpublic static IApplicationListener fromLookup(Construct scope, String id, ApplicationListenerLookupOptions options)public static IApplicationListener FromLookup(Construct scope, string id, ApplicationListenerLookupOptions options)func FromLookup(Scope Construct, Id *string, Options ApplicationListenerLookupOptions) IApplicationListenerstatic#
Look up an ApplicationListener.
isConstruct(x: any): boolean@staticmethod def is_construct(x: Any) -> boolpublic static Boolean isConstruct(Object x)public static bool IsConstruct(object x)func IsConstruct(X interface{}) *boolstatic#
Checks if `x` is a construct.
notes · 1 parameter · returns

Use this method instead of instanceof to properly detect Construct instances, even when the construct library is symlinked.

Explanation: in JavaScript, multiple copies of the constructs library on disk are seen as independent, completely different libraries. As a consequence, the class Construct in each copy of the constructs library is seen as a different class, and an instance of one class will not test as instanceof the other class. npm install will not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of the constructs library can be accidentally installed, and instanceof will behave unpredictably. It is safest to avoid using instanceof, and using this type-testing method instead.

Parameters

  • xxxxX — Any object.

Returns: true if x is an object created from a class which extends Construct.

isOwnedResource(construct: IConstruct): boolean@staticmethod def is_owned_resource(construct: IConstruct) -> boolpublic static Boolean isOwnedResource(IConstruct construct)public static bool IsOwnedResource(IConstruct construct)func IsOwnedResource(Construct IConstruct) *boolstatic#
Returns true if the construct was created by CDK, and false otherwise.
isResource(construct: IConstruct): boolean@staticmethod def is_resource(construct: IConstruct) -> boolpublic static Boolean isResource(IConstruct construct)public static bool IsResource(IConstruct construct)func IsResource(Construct IConstruct) *boolstatic#
Check whether the given construct is a Resource.
registerConnectable(connectable: IConnectable, portRange: Port): voiddef register_connectable(self, connectable: IConnectable, port_range: Port) -> Nonepublic void registerConnectable(IConnectable connectable, Port portRange)public void RegisterConnectable(IConnectable connectable, Port portRange)func RegisterConnectable(Connectable IConnectable, PortRange Port)#
Register that a connectable that has been added to this load balancer.

Don't call this directly. It is called by ApplicationTargetGroup.

removeAttribute(key: string): voiddef remove_attribute(self, key: str) -> Nonepublic void removeAttribute(String key)public void RemoveAttribute(string key)func RemoveAttribute(Key *string)#
Remove an attribute from the listener.
setAttribute(key: string, value?: string): voiddef set_attribute(self, key: str, value: typing.Optional[str] = None) -> Nonepublic void setAttribute(String key, String value)public void SetAttribute(string key, string? value = null)func SetAttribute(Key *string, Value *string)#
Set a non-standard attribute on the listener.
toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#
Returns a string representation of this construct.
with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#
Applies one or more mixins to this construct.

Mixins are applied in order. The list of constructs is captured at the start of the call, so constructs added by a mixin will not be visited. Use multiple with() calls if subsequent mixins should apply to added constructs.