@aws-cdk/aws-ecs-patterns: Not possible to use ApplicationLoadBalancedFargateService with existing ALB listener
Is it possible to use '@aws-cdk/aws-ecs-patterns' ApplicationLoadBalancedFargateService with existing ALB and existing Listeners? What would be the way to create multiple AWS ECS Fargate services and point to same listener. Also requirement is to set deploymentController for Fargate service to CodeDeploy(in order to trigger blue/green deployments). Does CDK have support for this?
Looks like it's not possible to use a common ALB and create a listener rule pointing to the new service created via: ApplicationLoadBalancedFargateService
I tried the following:
lb = elasticloadbalancingv2.ApplicationLoadBalancer.from_lookup(
self,
f"{props.namespace}-lb",
load_balancer_arn="<lb-arn>")
# Note this LB already has some listener rules configured
Then I create the service as:
svc= ecs_patterns.ApplicationLoadBalancedFargateService(
self,
... ,
load_balancer=lb,
CDK/CF tries to create a new listener rule for port 443 and fails with the following error:
Resource handler returned message: "Listener port '443' is already in use (Service: ElasticLoadBalancingV2, Status Code: 400,
I think it's a common usecase to create a common loadbalancer and add listeners + targets groups based on certain rules.
[EDIT]: I suppose it might make sense to use lower level constructs to achieve this - but I like the simplicity ApplicationLoadBalancedFargateService provides. And since we already allow using existing LB with the construct(with load_balancer=.. ), it would be further enhanced by adding a flag to not overwrite existing default listener during creation. We could add an additional rule later with eg. svc.listener.add_action,add_target etc...
At the moment, this is what is happening underneath the hood:
https://github.com/aws/aws-cdk/blob/2815a448ed7061740e60304d3f35beb97f66eb86/packages/%40aws-cdk/aws-ecs-patterns/lib/base/application-load-balanced-service-base.ts#L440-L445
The addListener function will always be called whether you import an existing load balancer or not. You are able to configure the port of the listener and if the listener is open to all traffic, but beyond that I can't find any ways to configure listeners further using our L3 construct.
For now, lower level classes will be required for any additional configuration.
It looks like quite a few people want to be able to configure this construct. The bug you linked relevant, but I don't think that satisfies all the requirements you guys need. If you'd like to see more functionality here, please submit a feature request! Let me know if you have further questions, and sorry for the wait here @awsiv and @CONJAUMCGCG
We have pretty much the same use case as @CONJAUMCGCG - one shared ALB for multiple services, which is set up separately from the services themselves in a different stack, plus be able to use blue-green deployments with these services, preferably.
Can you open a feature request for this @eriklz?
Created feature request, see #15894
⚠️COMMENT VISIBILITY WARNING⚠️
Comments on closed issues are hard for our team to see. If you need more assistance, please either tag a team member or open a new issue that references this one. If you wish to keep having a conversation with other community members under this issue feel free to do so.
I don't understand why this issue is closed? There is no resolution for this issue. We have the following setup:
- ECS for API
- ECS for WEB and a LB with forwarding rules. How am I supposed to link them if the ApplicationLoadBalancedFargateService construct creates a new LB every single time?!
This issue should not be closed. Should be reopened.
Are there any updates here? We really need this for our use case!
I have the same problem, any update?
What I ended up doing was using low-level constructs: for the load balancer: ApplicationLoadBalancer construct with 2 listeners (the first listener set up with an HTTP to HTTPS redirect and the second one with forwarding rules): e.g
private createLoadBalancer() {
this.elb = this.getLoadBalancer();
this.createHttpListener();
this.createHttpsListener();
}
private createHttpsListener() {
const httpsListener = this.elb.addListener("HTTPS", {
protocol: ApplicationProtocol.HTTPS,
port: 443,
sslPolicy: SslPolicy.FORWARD_SECRECY_TLS12_RES_GCM,
certificates: [{ certificateArn: "my-certificate-arn" }],
});
this.createAPIRule(httpsListener);
this.createWEBRule(httpsListener);
}
private createWEBRule(httpsListener: ApplicationListener) {
const webTargetGroup = new ApplicationTargetGroup(this, "WEB Target Group", {
targetType: TargetType.IP,
port: 80,
vpc: this.props.vpc,
targetGroupName: `web-${this.props.environment}-tg`,
targets: [this.props.webFargateService],
});
const webListenerAction = ListenerAction.forward([webTargetGroup]);
httpsListener.addAction("WEB Balancing", {
action: webListenerAction,
});
}
private createAPIRule(httpsListener: ApplicationListener) {
const apiTargetGroup = new ApplicationTargetGroup(this, "API Target Group", {
targetType: TargetType.IP,
port: 80,
vpc: this.props.vpc,
targetGroupName: `api-${this.props.environment}-tg`,
targets: [this.props.apiFargateService],
});
const apiListenerAction = ListenerAction.forward([apiTargetGroup]);
httpsListener.addAction("API Balancing", {
action: apiListenerAction,
priority: 1,
conditions: [ListenerCondition.pathPatterns(["/api/*"])],
});
}
private createHttpListener() {
const redirect = ListenerAction.redirect({
protocol: ApplicationProtocol.HTTPS,
port: "443",
host: "#{host}",
path: "/#{path}",
query: "#{query}",
permanent: true,
});
const httpListener = this.elb.addListener("HTTP", {
protocol: ApplicationProtocol.HTTP,
port: 80,
});
httpListener.addAction("HTTP Redirect", { action: redirect });
}
private getLoadBalancer(): IApplicationLoadBalancer {
const securityGroup = SecurityGroup.fromSecurityGroupId(this, "ELB Security Group", "my-security-group-id");
const elb = new ApplicationLoadBalancer(this, this.description, {
vpc: this.props.vpc,
loadBalancerName: `elb-${this.props.environment}-01`,
securityGroup: securityGroup,
vpcSubnets: { subnetType: SubnetType.PRIVATE_WITH_NAT, onePerAz: true },
});
elb.applyRemovalPolicy(RemovalPolicy.RETAIN);
return elb;
}
Note this line: targets: [this.props.apiFargateService], this is the reference to API Fargate Service, which you can define like this:
new FargateService(this, "API Fargate Service", {
serviceName: `api-${this.props.environment}-fargate-service`,
cluster: cluster,
securityGroups: [securityGroup],
desiredCount: 1,
taskDefinition: taskDefinition
});
sure, here you'll have to manually create the task definition, something like this:
public createTaskDefinition(executionRole: IRole, role: IRole): FargateTaskDefinition {
return new FargateTaskDefinition(this, "Fargate Task Definition API", {
family: `api-fargate-${this.props.environment}-td`,
memoryLimitMiB: 4096,
cpu: 1024,
executionRole,
taskRole: role
});
}
and the container
private createContainer(taskDefinition: FargateTaskDefinition) : void{
var container = taskDefinition.addContainer(`api-${this.props.environment}-container`, {
image: ContainerImage.fromRegistry(image)
});
container.addPortMappings({ containerPort: 80 });
container.addPortMappings({ containerPort: 443 });
}
but once you have the FargateService instance you can assign the reference to the ELB rule targets. I had to do the same thing for the web Fargate service and the good thing it's that now it's working... I know it's far from being perfect, but I guess that the ApplicationLoadBalancedFargateService it's a high-level construct and it's not designed to be that flexible.
Note that the execution roles or task roles are not mandatory, but in my case, they are provided, so I had to do a lookup first. Hope it helps.
What I ended up doing was using low-level constructs: for the load balancer: ApplicationLoadBalancer construct with 2 listeners (the first listener set up with an HTTP to HTTPS redirect and the second one with forwarding rules): e.g
private createLoadBalancer() { this.elb = this.getLoadBalancer(); this.createHttpListener(); this.createHttpsListener(); } private createHttpsListener() { const httpsListener = this.elb.addListener("HTTPS", { protocol: ApplicationProtocol.HTTPS, port: 443, sslPolicy: SslPolicy.FORWARD_SECRECY_TLS12_RES_GCM, certificates: [{ certificateArn: "my-certificate-arn" }], }); this.createAPIRule(httpsListener); this.createWEBRule(httpsListener); } private createWEBRule(httpsListener: ApplicationListener) { const webTargetGroup = new ApplicationTargetGroup(this, "WEB Target Group", { targetType: TargetType.IP, port: 80, vpc: this.props.vpc, targetGroupName: `web-${this.props.environment}-tg`, targets: [this.props.webFargateService], }); const webListenerAction = ListenerAction.forward([webTargetGroup]); httpsListener.addAction("WEB Balancing", { action: webListenerAction, }); } private createAPIRule(httpsListener: ApplicationListener) { const apiTargetGroup = new ApplicationTargetGroup(this, "API Target Group", { targetType: TargetType.IP, port: 80, vpc: this.props.vpc, targetGroupName: `api-${this.props.environment}-tg`, targets: [this.props.apiFargateService], }); const apiListenerAction = ListenerAction.forward([apiTargetGroup]); httpsListener.addAction("API Balancing", { action: apiListenerAction, priority: 1, conditions: [ListenerCondition.pathPatterns(["/api/*"])], }); } private createHttpListener() { const redirect = ListenerAction.redirect({ protocol: ApplicationProtocol.HTTPS, port: "443", host: "#{host}", path: "/#{path}", query: "#{query}", permanent: true, }); const httpListener = this.elb.addListener("HTTP", { protocol: ApplicationProtocol.HTTP, port: 80, }); httpListener.addAction("HTTP Redirect", { action: redirect }); } private getLoadBalancer(): IApplicationLoadBalancer { const securityGroup = SecurityGroup.fromSecurityGroupId(this, "ELB Security Group", "my-security-group-id"); const elb = new ApplicationLoadBalancer(this, this.description, { vpc: this.props.vpc, loadBalancerName: `elb-${this.props.environment}-01`, securityGroup: securityGroup, vpcSubnets: { subnetType: SubnetType.PRIVATE_WITH_NAT, onePerAz: true }, }); elb.applyRemovalPolicy(RemovalPolicy.RETAIN); return elb; }Note this line: targets: [this.props.apiFargateService], this is the reference to API Fargate Service, which you can define like this:
new FargateService(this, "API Fargate Service", { serviceName: `api-${this.props.environment}-fargate-service`, cluster: cluster, securityGroups: [securityGroup], desiredCount: 1, taskDefinition: taskDefinition });sure, here you'll have to manually create the task definition, something like this:
public createTaskDefinition(executionRole: IRole, role: IRole): FargateTaskDefinition { return new FargateTaskDefinition(this, "Fargate Task Definition API", { family: `api-fargate-${this.props.environment}-td`, memoryLimitMiB: 4096, cpu: 1024, executionRole, taskRole: role }); }and the container
private createContainer(taskDefinition: FargateTaskDefinition) : void{ var container = taskDefinition.addContainer(`api-${this.props.environment}-container`, { image: ContainerImage.fromRegistry(image) }); container.addPortMappings({ containerPort: 80 }); container.addPortMappings({ containerPort: 443 }); }but once you have the FargateService instance you can assign the reference to the ELB rule targets. I had to do the same thing for the web Fargate service and the good thing it's that now it's working... I know it's far from being perfect, but I guess that the ApplicationLoadBalancedFargateService it's a high-level construct and it's not designed to be that flexible.
Note that the execution roles or task roles are not mandatory, but in my case, they are provided, so I had to do a lookup first. Hope it helps.
But you are still creating the load balancer with ApplicationLoadBalancer, and that will create a extra listener and target group
Yes indeed, but this is what I want do to. I want to have different health checks for each target group.