Package software.amazon.awscdk.services.ecs.patterns


package software.amazon.awscdk.services.ecs.patterns

CDK Construct library for higher-level ECS Constructs

This library provides higher-level Amazon ECS constructs which follow common architectural patterns. It contains:

  • Application Load Balanced Services
  • Network Load Balanced Services
  • Queue Processing Services
  • Scheduled Tasks (cron jobs)
  • Additional Examples

Application Load Balanced Services

To define an Amazon ECS service that is behind an application load balancer, instantiate one of the following:

  • ApplicationLoadBalancedEc2Service

 Cluster cluster;
 
 ApplicationLoadBalancedEc2Service loadBalancedEcsService = ApplicationLoadBalancedEc2Service.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(1024)
         .taskImageOptions(ApplicationLoadBalancedTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("test"))
                 .environment(Map.of(
                         "TEST_ENVIRONMENT_VARIABLE1", "test environment variable 1 value",
                         "TEST_ENVIRONMENT_VARIABLE2", "test environment variable 2 value"))
                 .command(List.of("command"))
                 .entryPoint(List.of("entry", "point"))
                 .build())
         .desiredCount(2)
         .build();
 

  • ApplicationLoadBalancedFargateService

 Cluster cluster;
 
 ApplicationLoadBalancedFargateService loadBalancedFargateService = ApplicationLoadBalancedFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(1024)
         .cpu(512)
         .taskImageOptions(ApplicationLoadBalancedTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .command(List.of("command"))
                 .entryPoint(List.of("entry", "point"))
                 .build())
         .build();
 
 loadBalancedFargateService.targetGroup.configureHealthCheck(HealthCheck.builder()
         .path("/custom-health-path")
         .build());
 

Instead of providing a cluster you can specify a VPC and CDK will create a new ECS cluster. If you deploy multiple services CDK will only create one cluster per VPC.

You can omit cluster and vpc to let CDK create a new VPC with two AZs and create a cluster inside this VPC.

You can customize the health check for your target group; otherwise it defaults to HTTP over port 80 hitting path /.

You can customize the health check configuration of the container via the healthCheck property; otherwise it defaults to the health check configuration from the container.

Fargate services will use the LATEST platform version by default, but you can override by providing a value for the platformVersion property in the constructor.

Fargate services use the default VPC Security Group unless one or more are provided using the securityGroups property in the constructor.

By setting redirectHTTP to true, CDK will automatically create a listener on port 80 that redirects HTTP traffic to the HTTPS port.

If you specify the option recordType you can decide if you want the construct to use CNAME or Route53-Aliases as record sets.

If you need to encrypt the traffic between the load balancer and the ECS tasks, you can set the targetProtocol to HTTPS.

Additionally, if more than one application target group are needed, instantiate one of the following:

  • ApplicationMultipleTargetGroupsEc2Service

 // One application load balancer with one listener and two target groups.
 Cluster cluster;
 
 ApplicationMultipleTargetGroupsEc2Service loadBalancedEc2Service = ApplicationMultipleTargetGroupsEc2Service.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(256)
         .taskImageOptions(ApplicationLoadBalancedTaskImageProps.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .build())
         .targetGroups(List.of(ApplicationTargetProps.builder()
                 .containerPort(80)
                 .build(), ApplicationTargetProps.builder()
                 .containerPort(90)
                 .pathPattern("a/b/c")
                 .priority(10)
                 .build()))
         .build();
 

  • ApplicationMultipleTargetGroupsFargateService

 // One application load balancer with one listener and two target groups.
 Cluster cluster;
 
 ApplicationMultipleTargetGroupsFargateService loadBalancedFargateService = ApplicationMultipleTargetGroupsFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(1024)
         .cpu(512)
         .taskImageOptions(ApplicationLoadBalancedTaskImageProps.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .build())
         .targetGroups(List.of(ApplicationTargetProps.builder()
                 .containerPort(80)
                 .build(), ApplicationTargetProps.builder()
                 .containerPort(90)
                 .pathPattern("a/b/c")
                 .priority(10)
                 .build()))
         .build();
 

Network Load Balanced Services

To define an Amazon ECS service that is behind a network load balancer, instantiate one of the following:

  • NetworkLoadBalancedEc2Service

 Cluster cluster;
 
 NetworkLoadBalancedEc2Service loadBalancedEcsService = NetworkLoadBalancedEc2Service.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(1024)
         .taskImageOptions(NetworkLoadBalancedTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("test"))
                 .environment(Map.of(
                         "TEST_ENVIRONMENT_VARIABLE1", "test environment variable 1 value",
                         "TEST_ENVIRONMENT_VARIABLE2", "test environment variable 2 value"))
                 .build())
         .desiredCount(2)
         .build();
 

  • NetworkLoadBalancedFargateService

 Cluster cluster;
 
 NetworkLoadBalancedFargateService loadBalancedFargateService = NetworkLoadBalancedFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(1024)
         .cpu(512)
         .taskImageOptions(NetworkLoadBalancedTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .build())
         .build();
 

The CDK will create a new Amazon ECS cluster if you specify a VPC and omit cluster. If you deploy multiple services the CDK will only create one cluster per VPC.

If cluster and vpc are omitted, the CDK creates a new VPC with subnets in two Availability Zones and a cluster within this VPC.

If you specify the option recordType you can decide if you want the construct to use CNAME or Route53-Aliases as record sets.

Additionally, if more than one network target group is needed, instantiate one of the following:

  • NetworkMultipleTargetGroupsEc2Service

 // Two network load balancers, each with their own listener and target group.
 Cluster cluster;
 
 NetworkMultipleTargetGroupsEc2Service loadBalancedEc2Service = NetworkMultipleTargetGroupsEc2Service.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(256)
         .taskImageOptions(NetworkLoadBalancedTaskImageProps.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .build())
         .loadBalancers(List.of(NetworkLoadBalancerProps.builder()
                 .name("lb1")
                 .listeners(List.of(NetworkListenerProps.builder()
                         .name("listener1")
                         .build()))
                 .build(), NetworkLoadBalancerProps.builder()
                 .name("lb2")
                 .listeners(List.of(NetworkListenerProps.builder()
                         .name("listener2")
                         .build()))
                 .build()))
         .targetGroups(List.of(NetworkTargetProps.builder()
                 .containerPort(80)
                 .listener("listener1")
                 .build(), NetworkTargetProps.builder()
                 .containerPort(90)
                 .listener("listener2")
                 .build()))
         .build();
 

  • NetworkMultipleTargetGroupsFargateService

 // Two network load balancers, each with their own listener and target group.
 Cluster cluster;
 
 NetworkMultipleTargetGroupsFargateService loadBalancedFargateService = NetworkMultipleTargetGroupsFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(512)
         .taskImageOptions(NetworkLoadBalancedTaskImageProps.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .build())
         .loadBalancers(List.of(NetworkLoadBalancerProps.builder()
                 .name("lb1")
                 .listeners(List.of(NetworkListenerProps.builder()
                         .name("listener1")
                         .build()))
                 .build(), NetworkLoadBalancerProps.builder()
                 .name("lb2")
                 .listeners(List.of(NetworkListenerProps.builder()
                         .name("listener2")
                         .build()))
                 .build()))
         .targetGroups(List.of(NetworkTargetProps.builder()
                 .containerPort(80)
                 .listener("listener1")
                 .build(), NetworkTargetProps.builder()
                 .containerPort(90)
                 .listener("listener2")
                 .build()))
         .build();
 

Queue Processing Services

To define a service that creates a queue and reads from that queue, instantiate one of the following:

  • QueueProcessingEc2Service

 Cluster cluster;
 
 QueueProcessingEc2Service queueProcessingEc2Service = QueueProcessingEc2Service.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(1024)
         .image(ContainerImage.fromRegistry("test"))
         .command(List.of("-c", "4", "amazon.com"))
         .enableLogging(false)
         .desiredTaskCount(2)
         .environment(Map.of(
                 "TEST_ENVIRONMENT_VARIABLE1", "test environment variable 1 value",
                 "TEST_ENVIRONMENT_VARIABLE2", "test environment variable 2 value"))
         .maxScalingCapacity(5)
         .containerName("test")
         .build();
 

  • QueueProcessingFargateService

 Cluster cluster;
 
 QueueProcessingFargateService queueProcessingFargateService = QueueProcessingFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(512)
         .image(ContainerImage.fromRegistry("test"))
         .command(List.of("-c", "4", "amazon.com"))
         .enableLogging(false)
         .desiredTaskCount(2)
         .environment(Map.of(
                 "TEST_ENVIRONMENT_VARIABLE1", "test environment variable 1 value",
                 "TEST_ENVIRONMENT_VARIABLE2", "test environment variable 2 value"))
         .maxScalingCapacity(5)
         .containerName("test")
         .build();
 

when queue not provided by user, CDK will create a primary queue and a dead letter queue with default redrive policy and attach permission to the task to be able to access the primary queue.

NOTE: QueueProcessingFargateService adds a CPU Based scaling strategy by default. You can turn this off by setting disableCpuBasedScaling: true.

 Cluster cluster;
 
 QueueProcessingFargateService queueProcessingFargateService = QueueProcessingFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(512)
         .image(ContainerImage.fromRegistry("test"))
         .command(List.of("-c", "4", "amazon.com"))
         .enableLogging(false)
         .desiredTaskCount(2)
         .environment(Map.of(
                 "TEST_ENVIRONMENT_VARIABLE1", "test environment variable 1 value",
                 "TEST_ENVIRONMENT_VARIABLE2", "test environment variable 2 value"))
         .maxScalingCapacity(5)
         .containerName("test")
         .disableCpuBasedScaling(true)
         .build();
 

To specify a custom target CPU utilization percentage for the scaling strategy use the cpuTargetUtilizationPercent property:

 Cluster cluster;
 
 QueueProcessingFargateService queueProcessingFargateService = QueueProcessingFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(512)
         .image(ContainerImage.fromRegistry("test"))
         .command(List.of("-c", "4", "amazon.com"))
         .enableLogging(false)
         .desiredTaskCount(2)
         .environment(Map.of())
         .maxScalingCapacity(5)
         .containerName("test")
         .cpuTargetUtilizationPercent(90)
         .build();
 

Scheduled Tasks

To define a task that runs periodically, there are 2 options:

  • ScheduledEc2Task

 // Instantiate an Amazon EC2 Task to run at a scheduled interval
 Cluster cluster;
 
 ScheduledEc2Task ecsScheduledTask = ScheduledEc2Task.Builder.create(this, "ScheduledTask")
         .cluster(cluster)
         .scheduledEc2TaskImageOptions(ScheduledEc2TaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .memoryLimitMiB(256)
                 .environment(Map.of("name", "TRIGGER", "value", "CloudWatch Events"))
                 .build())
         .schedule(Schedule.expression("rate(1 minute)"))
         .enabled(true)
         .ruleName("sample-scheduled-task-rule")
         .build();
 

  • ScheduledFargateTask

 Cluster cluster;
 
 ScheduledFargateTask scheduledFargateTask = ScheduledFargateTask.Builder.create(this, "ScheduledFargateTask")
         .cluster(cluster)
         .scheduledFargateTaskImageOptions(ScheduledFargateTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .memoryLimitMiB(512)
                 .build())
         .schedule(Schedule.expression("rate(1 minute)"))
         .platformVersion(FargatePlatformVersion.LATEST)
         .build();
 

Additional Examples

In addition to using the constructs, users can also add logic to customize these constructs:

Configure HTTPS on an ApplicationLoadBalancedFargateService

 import software.amazon.awscdk.services.route53.HostedZone;
 import software.amazon.awscdk.services.certificatemanager.Certificate;
 import software.amazon.awscdk.services.elasticloadbalancingv2.SslPolicy;
 
 Vpc vpc;
 Cluster cluster;
 
 
 IHostedZone domainZone = HostedZone.fromLookup(this, "Zone", HostedZoneProviderProps.builder().domainName("example.com").build());
 ICertificate certificate = Certificate.fromCertificateArn(this, "Cert", "arn:aws:acm:us-east-1:123456:certificate/abcdefg");
 ApplicationLoadBalancedFargateService loadBalancedFargateService = ApplicationLoadBalancedFargateService.Builder.create(this, "Service")
         .vpc(vpc)
         .cluster(cluster)
         .certificate(certificate)
         .sslPolicy(SslPolicy.RECOMMENDED)
         .domainName("api.example.com")
         .domainZone(domainZone)
         .redirectHTTP(true)
         .taskImageOptions(ApplicationLoadBalancedTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .build())
         .build();
 

Set capacityProviderStrategies for ApplicationLoadBalancedFargateService

 Cluster cluster;
 
 cluster.enableFargateCapacityProviders();
 
 ApplicationLoadBalancedFargateService loadBalancedFargateService = ApplicationLoadBalancedFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .taskImageOptions(ApplicationLoadBalancedTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .build())
         .capacityProviderStrategies(List.of(CapacityProviderStrategy.builder()
                 .capacityProvider("FARGATE_SPOT")
                 .weight(2)
                 .base(0)
                 .build(), CapacityProviderStrategy.builder()
                 .capacityProvider("FARGATE")
                 .weight(1)
                 .base(1)
                 .build()))
         .build();
 

Add Schedule-Based Auto-Scaling to an ApplicationLoadBalancedFargateService

 Cluster cluster;
 
 ApplicationLoadBalancedFargateService loadBalancedFargateService = ApplicationLoadBalancedFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(1024)
         .desiredCount(1)
         .cpu(512)
         .taskImageOptions(ApplicationLoadBalancedTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .build())
         .build();
 
 ScalableTaskCount scalableTarget = loadBalancedFargateService.service.autoScaleTaskCount(EnableScalingProps.builder()
         .minCapacity(5)
         .maxCapacity(20)
         .build());
 
 scalableTarget.scaleOnSchedule("DaytimeScaleDown", ScalingSchedule.builder()
         .schedule(Schedule.cron(CronOptions.builder().hour("8").minute("0").build()))
         .minCapacity(1)
         .build());
 
 scalableTarget.scaleOnSchedule("EveningRushScaleUp", ScalingSchedule.builder()
         .schedule(Schedule.cron(CronOptions.builder().hour("20").minute("0").build()))
         .minCapacity(10)
         .build());
 

Add Metric-Based Auto-Scaling to an ApplicationLoadBalancedFargateService

 Cluster cluster;
 
 ApplicationLoadBalancedFargateService loadBalancedFargateService = ApplicationLoadBalancedFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(1024)
         .desiredCount(1)
         .cpu(512)
         .taskImageOptions(ApplicationLoadBalancedTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .build())
         .build();
 
 ScalableTaskCount scalableTarget = loadBalancedFargateService.service.autoScaleTaskCount(EnableScalingProps.builder()
         .minCapacity(1)
         .maxCapacity(20)
         .build());
 
 scalableTarget.scaleOnCpuUtilization("CpuScaling", CpuUtilizationScalingProps.builder()
         .targetUtilizationPercent(50)
         .build());
 
 scalableTarget.scaleOnMemoryUtilization("MemoryScaling", MemoryUtilizationScalingProps.builder()
         .targetUtilizationPercent(50)
         .build());
 

Change the default Deployment Controller

 Cluster cluster;
 
 ApplicationLoadBalancedFargateService loadBalancedFargateService = ApplicationLoadBalancedFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(1024)
         .desiredCount(1)
         .cpu(512)
         .taskImageOptions(ApplicationLoadBalancedTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .build())
         .deploymentController(DeploymentController.builder()
                 .type(DeploymentControllerType.CODE_DEPLOY)
                 .build())
         .build();
 

Deployment circuit breaker and rollback

Amazon ECS deployment circuit breaker automatically rolls back unhealthy service deployments without the need for manual intervention. Use circuitBreaker to enable deployment circuit breaker and optionally enable rollback for automatic rollback. See Using the deployment circuit breaker for more details.

 Cluster cluster;
 
 ApplicationLoadBalancedFargateService service = ApplicationLoadBalancedFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(1024)
         .desiredCount(1)
         .cpu(512)
         .taskImageOptions(ApplicationLoadBalancedTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .build())
         .circuitBreaker(DeploymentCircuitBreaker.builder().rollback(true).build())
         .build();
 

Set deployment configuration on QueueProcessingService

 Cluster cluster;
 
 QueueProcessingFargateService queueProcessingFargateService = QueueProcessingFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(512)
         .image(ContainerImage.fromRegistry("test"))
         .command(List.of("-c", "4", "amazon.com"))
         .enableLogging(false)
         .desiredTaskCount(2)
         .environment(Map.of())
         .maxScalingCapacity(5)
         .maxHealthyPercent(200)
         .minHealthyPercent(66)
         .build();
 

Set taskSubnets and securityGroups for QueueProcessingFargateService

 Vpc vpc;
 SecurityGroup securityGroup;
 
 QueueProcessingFargateService queueProcessingFargateService = QueueProcessingFargateService.Builder.create(this, "Service")
         .vpc(vpc)
         .memoryLimitMiB(512)
         .image(ContainerImage.fromRegistry("test"))
         .securityGroups(List.of(securityGroup))
         .taskSubnets(SubnetSelection.builder().subnetType(SubnetType.PRIVATE_ISOLATED).build())
         .build();
 

Define tasks with public IPs for QueueProcessingFargateService

 Vpc vpc;
 
 QueueProcessingFargateService queueProcessingFargateService = QueueProcessingFargateService.Builder.create(this, "Service")
         .vpc(vpc)
         .memoryLimitMiB(512)
         .image(ContainerImage.fromRegistry("test"))
         .assignPublicIp(true)
         .build();
 

Define tasks with custom queue parameters for QueueProcessingFargateService

 Vpc vpc;
 
 QueueProcessingFargateService queueProcessingFargateService = QueueProcessingFargateService.Builder.create(this, "Service")
         .vpc(vpc)
         .memoryLimitMiB(512)
         .image(ContainerImage.fromRegistry("test"))
         .maxReceiveCount(42)
         .retentionPeriod(Duration.days(7))
         .visibilityTimeout(Duration.minutes(5))
         .build();
 

Set cooldown for QueueProcessingFargateService

The cooldown period is the amount of time to wait for a previous scaling activity to take effect. To specify something other than the default cooldown period of 300 seconds, use the cooldown parameter:

 Vpc vpc;
 
 QueueProcessingFargateService queueProcessingFargateService = QueueProcessingFargateService.Builder.create(this, "Service")
         .vpc(vpc)
         .memoryLimitMiB(512)
         .image(ContainerImage.fromRegistry("test"))
         .assignPublicIp(true)
         .cooldown(Duration.seconds(500))
         .build();
 

Set capacityProviderStrategies for QueueProcessingFargateService

 Cluster cluster;
 
 cluster.enableFargateCapacityProviders();
 
 QueueProcessingFargateService queueProcessingFargateService = QueueProcessingFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(512)
         .image(ContainerImage.fromRegistry("test"))
         .capacityProviderStrategies(List.of(CapacityProviderStrategy.builder()
                 .capacityProvider("FARGATE_SPOT")
                 .weight(2)
                 .build(), CapacityProviderStrategy.builder()
                 .capacityProvider("FARGATE")
                 .weight(1)
                 .build()))
         .build();
 

Set a custom container-level Healthcheck for QueueProcessingFargateService

 Vpc vpc;
 SecurityGroup securityGroup;
 
 QueueProcessingFargateService queueProcessingFargateService = QueueProcessingFargateService.Builder.create(this, "Service")
         .vpc(vpc)
         .memoryLimitMiB(512)
         .image(ContainerImage.fromRegistry("test"))
         .healthCheck(HealthCheck.builder()
                 .command(List.of("CMD-SHELL", "curl -f http://localhost/ || exit 1"))
                 // the properties below are optional
                 .interval(Duration.minutes(30))
                 .retries(123)
                 .startPeriod(Duration.minutes(30))
                 .timeout(Duration.minutes(30))
                 .build())
         .build();
 

Set capacityProviderStrategies for QueueProcessingEc2Service

 import software.amazon.awscdk.services.autoscaling.*;
 
 
 Vpc vpc = Vpc.Builder.create(this, "Vpc").maxAzs(1).build();
 Cluster cluster = Cluster.Builder.create(this, "EcsCluster").vpc(vpc).build();
 AutoScalingGroup autoScalingGroup = AutoScalingGroup.Builder.create(this, "asg")
         .vpc(vpc)
         .instanceType(InstanceType.of(InstanceClass.BURSTABLE2, InstanceSize.MICRO))
         .machineImage(EcsOptimizedImage.amazonLinux2())
         .build();
 AsgCapacityProvider capacityProvider = AsgCapacityProvider.Builder.create(this, "provider")
         .autoScalingGroup(autoScalingGroup)
         .build();
 cluster.addAsgCapacityProvider(capacityProvider);
 
 QueueProcessingEc2Service queueProcessingEc2Service = QueueProcessingEc2Service.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(512)
         .image(ContainerImage.fromRegistry("test"))
         .capacityProviderStrategies(List.of(CapacityProviderStrategy.builder()
                 .capacityProvider(capacityProvider.getCapacityProviderName())
                 .build()))
         .build();
 

Select specific vpc subnets for ApplicationLoadBalancedFargateService

 Cluster cluster;
 
 ApplicationLoadBalancedFargateService loadBalancedFargateService = ApplicationLoadBalancedFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(1024)
         .desiredCount(1)
         .cpu(512)
         .taskImageOptions(ApplicationLoadBalancedTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .build())
         .taskSubnets(SubnetSelection.builder()
                 .subnets(List.of(Subnet.fromSubnetId(this, "subnet", "VpcISOLATEDSubnet1Subnet80F07FA0")))
                 .build())
         .build();
 

Select idleTimeout for ApplicationLoadBalancedFargateService

 Cluster cluster;
 
 ApplicationLoadBalancedFargateService loadBalancedFargateService = ApplicationLoadBalancedFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(1024)
         .desiredCount(1)
         .cpu(512)
         .taskImageOptions(ApplicationLoadBalancedTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .build())
         .idleTimeout(Duration.seconds(120))
         .build();
 

Select idleTimeout for ApplicationMultipleTargetGroupsFargateService

 import software.amazon.awscdk.services.certificatemanager.Certificate;
 import software.amazon.awscdk.services.ec2.InstanceType;
 import software.amazon.awscdk.services.ecs.Cluster;
 import software.amazon.awscdk.services.ecs.ContainerImage;
 import software.amazon.awscdk.services.elasticloadbalancingv2.ApplicationProtocol;
 import software.amazon.awscdk.services.elasticloadbalancingv2.SslPolicy;
 import software.amazon.awscdk.services.route53.PublicHostedZone;
 
 Vpc vpc = Vpc.Builder.create(this, "Vpc").maxAzs(1).build();
 ApplicationMultipleTargetGroupsFargateService loadBalancedFargateService = ApplicationMultipleTargetGroupsFargateService.Builder.create(this, "myService")
         .cluster(Cluster.Builder.create(this, "EcsCluster").vpc(vpc).build())
         .memoryLimitMiB(256)
         .taskImageOptions(ApplicationLoadBalancedTaskImageProps.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .build())
         .enableExecuteCommand(true)
         .loadBalancers(List.of(ApplicationLoadBalancerProps.builder()
                 .name("lb")
                 .idleTimeout(Duration.seconds(400))
                 .domainName("api.example.com")
                 .domainZone(PublicHostedZone.Builder.create(this, "HostedZone").zoneName("example.com").build())
                 .listeners(List.of(ApplicationListenerProps.builder()
                         .name("listener")
                         .protocol(ApplicationProtocol.HTTPS)
                         .certificate(Certificate.fromCertificateArn(this, "Cert", "helloworld"))
                         .sslPolicy(SslPolicy.TLS12_EXT)
                         .build()))
                 .build(), ApplicationLoadBalancerProps.builder()
                 .name("lb2")
                 .idleTimeout(Duration.seconds(120))
                 .domainName("frontend.com")
                 .domainZone(PublicHostedZone.Builder.create(this, "HostedZone").zoneName("frontend.com").build())
                 .listeners(List.of(ApplicationListenerProps.builder()
                         .name("listener2")
                         .protocol(ApplicationProtocol.HTTPS)
                         .certificate(Certificate.fromCertificateArn(this, "Cert2", "helloworld"))
                         .sslPolicy(SslPolicy.TLS12_EXT)
                         .build()))
                 .build()))
         .targetGroups(List.of(ApplicationTargetProps.builder()
                 .containerPort(80)
                 .listener("listener")
                 .build(), ApplicationTargetProps.builder()
                 .containerPort(90)
                 .pathPattern("a/b/c")
                 .priority(10)
                 .listener("listener")
                 .build(), ApplicationTargetProps.builder()
                 .containerPort(443)
                 .listener("listener2")
                 .build(), ApplicationTargetProps.builder()
                 .containerPort(80)
                 .pathPattern("a/b/c")
                 .priority(10)
                 .listener("listener2")
                 .build()))
         .build();
 

Set health checks for ApplicationMultipleTargetGroupsFargateService

 import software.amazon.awscdk.services.certificatemanager.Certificate;
 import software.amazon.awscdk.services.ec2.InstanceType;
 import software.amazon.awscdk.services.ecs.Cluster;
 import software.amazon.awscdk.services.ecs.ContainerImage;
 import software.amazon.awscdk.services.elasticloadbalancingv2.ApplicationProtocol;
 import software.amazon.awscdk.services.elasticloadbalancingv2.Protocol;
 import software.amazon.awscdk.services.elasticloadbalancingv2.SslPolicy;
 import software.amazon.awscdk.services.route53.PublicHostedZone;
 
 Vpc vpc = Vpc.Builder.create(this, "Vpc").maxAzs(1).build();
 
 ApplicationMultipleTargetGroupsFargateService loadBalancedFargateService = ApplicationMultipleTargetGroupsFargateService.Builder.create(this, "myService")
         .cluster(Cluster.Builder.create(this, "EcsCluster").vpc(vpc).build())
         .memoryLimitMiB(256)
         .taskImageOptions(ApplicationLoadBalancedTaskImageProps.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .build())
         .enableExecuteCommand(true)
         .loadBalancers(List.of(ApplicationLoadBalancerProps.builder()
                 .name("lb")
                 .idleTimeout(Duration.seconds(400))
                 .domainName("api.example.com")
                 .domainZone(PublicHostedZone.Builder.create(this, "HostedZone").zoneName("example.com").build())
                 .listeners(List.of(ApplicationListenerProps.builder()
                         .name("listener")
                         .protocol(ApplicationProtocol.HTTPS)
                         .certificate(Certificate.fromCertificateArn(this, "Cert", "helloworld"))
                         .sslPolicy(SslPolicy.TLS12_EXT)
                         .build()))
                 .build(), ApplicationLoadBalancerProps.builder()
                 .name("lb2")
                 .idleTimeout(Duration.seconds(120))
                 .domainName("frontend.com")
                 .domainZone(PublicHostedZone.Builder.create(this, "HostedZone").zoneName("frontend.com").build())
                 .listeners(List.of(ApplicationListenerProps.builder()
                         .name("listener2")
                         .protocol(ApplicationProtocol.HTTPS)
                         .certificate(Certificate.fromCertificateArn(this, "Cert2", "helloworld"))
                         .sslPolicy(SslPolicy.TLS12_EXT)
                         .build()))
                 .build()))
         .targetGroups(List.of(ApplicationTargetProps.builder()
                 .containerPort(80)
                 .listener("listener")
                 .build(), ApplicationTargetProps.builder()
                 .containerPort(90)
                 .pathPattern("a/b/c")
                 .priority(10)
                 .listener("listener")
                 .build(), ApplicationTargetProps.builder()
                 .containerPort(443)
                 .listener("listener2")
                 .build(), ApplicationTargetProps.builder()
                 .containerPort(80)
                 .pathPattern("a/b/c")
                 .priority(10)
                 .listener("listener2")
                 .build()))
         .build();
 
 loadBalancedFargateService.targetGroups[0].configureHealthCheck(HealthCheck.builder()
         .port("8050")
         .protocol(Protocol.HTTP)
         .healthyThresholdCount(2)
         .unhealthyThresholdCount(2)
         .timeout(Duration.seconds(10))
         .interval(Duration.seconds(30))
         .healthyHttpCodes("200")
         .build());
 
 loadBalancedFargateService.targetGroups[1].configureHealthCheck(HealthCheck.builder()
         .port("8050")
         .protocol(Protocol.HTTP)
         .healthyThresholdCount(2)
         .unhealthyThresholdCount(2)
         .timeout(Duration.seconds(10))
         .interval(Duration.seconds(30))
         .healthyHttpCodes("200")
         .build());
 

Set runtimePlatform for ApplicationLoadBalancedFargateService

 Cluster cluster;
 
 ApplicationLoadBalancedFargateService applicationLoadBalancedFargateService = ApplicationLoadBalancedFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(512)
         .taskImageOptions(ApplicationLoadBalancedTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .build())
         .runtimePlatform(RuntimePlatform.builder()
                 .cpuArchitecture(CpuArchitecture.ARM64)
                 .operatingSystemFamily(OperatingSystemFamily.LINUX)
                 .build())
         .build();
 

Set PlatformVersion for ScheduledFargateTask

 Cluster cluster;
 
 ScheduledFargateTask scheduledFargateTask = ScheduledFargateTask.Builder.create(this, "ScheduledFargateTask")
         .cluster(cluster)
         .scheduledFargateTaskImageOptions(ScheduledFargateTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .memoryLimitMiB(512)
                 .build())
         .schedule(Schedule.expression("rate(1 minute)"))
         .platformVersion(FargatePlatformVersion.VERSION1_4)
         .build();
 

Set SecurityGroups for ScheduledFargateTask

 Vpc vpc = Vpc.Builder.create(this, "Vpc").maxAzs(1).build();
 Cluster cluster = Cluster.Builder.create(this, "EcsCluster").vpc(vpc).build();
 SecurityGroup securityGroup = SecurityGroup.Builder.create(this, "SG").vpc(vpc).build();
 
 ScheduledFargateTask scheduledFargateTask = ScheduledFargateTask.Builder.create(this, "ScheduledFargateTask")
         .cluster(cluster)
         .scheduledFargateTaskImageOptions(ScheduledFargateTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .memoryLimitMiB(512)
                 .build())
         .schedule(Schedule.expression("rate(1 minute)"))
         .securityGroups(List.of(securityGroup))
         .build();
 

Deploy application and metrics sidecar

The following is an example of deploying an application along with a metrics sidecar container that utilizes dockerLabels for discovery:

 Cluster cluster;
 Vpc vpc;
 
 ApplicationLoadBalancedFargateService service = ApplicationLoadBalancedFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .vpc(vpc)
         .desiredCount(1)
         .taskImageOptions(ApplicationLoadBalancedTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .dockerLabels(Map.of(
                         "application.label.one", "first_label",
                         "application.label.two", "second_label"))
                 .build())
         .build();
 
 service.taskDefinition.addContainer("Sidecar", ContainerDefinitionOptions.builder()
         .image(ContainerImage.fromRegistry("example/metrics-sidecar"))
         .build());
 

Select specific load balancer name ApplicationLoadBalancedFargateService

 Cluster cluster;
 
 ApplicationLoadBalancedFargateService loadBalancedFargateService = ApplicationLoadBalancedFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(1024)
         .desiredCount(1)
         .cpu(512)
         .taskImageOptions(ApplicationLoadBalancedTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .build())
         .taskSubnets(SubnetSelection.builder()
                 .subnets(List.of(Subnet.fromSubnetId(this, "subnet", "VpcISOLATEDSubnet1Subnet80F07FA0")))
                 .build())
         .loadBalancerName("application-lb-name")
         .build();
 

ECS Exec

You can use ECS Exec to run commands in or get a shell to a container running on an Amazon EC2 instance or on AWS Fargate. Enable ECS Exec, by setting enableExecuteCommand to true.

ECS Exec is supported by all Services i.e. ApplicationLoadBalanced(Fargate|Ec2)Service, ApplicationMultipleTargetGroups(Fargate|Ec2)Service, NetworkLoadBalanced(Fargate|Ec2)Service, NetworkMultipleTargetGroups(Fargate|Ec2)Service, QueueProcessing(Fargate|Ec2)Service. It is not supported for ScheduledTasks.

Read more about ECS Exec in the ECS Developer Guide.

Example:

 Cluster cluster;
 
 ApplicationLoadBalancedFargateService loadBalancedFargateService = ApplicationLoadBalancedFargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .memoryLimitMiB(1024)
         .desiredCount(1)
         .cpu(512)
         .taskImageOptions(ApplicationLoadBalancedTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .build())
         .enableExecuteCommand(true)
         .build();
 

Please note, ECS Exec leverages AWS Systems Manager (SSM). So as a prerequisite for the exec command to work, you need to have the SSM plugin for the AWS CLI installed locally. For more information, see Install Session Manager plugin for AWS CLI.

Propagate Tags from task definition for ScheduledFargateTask

For tasks that are defined by a Task Definition, tags applied to the definition will not be applied to the running task by default. To get this behavior, set propagateTags to ecs.PropagatedTagSource.TASK_DEFINITION as shown below:

 import software.amazon.awscdk.Tags;
 
 
 Vpc vpc = Vpc.Builder.create(this, "Vpc").maxAzs(1).build();
 Cluster cluster = Cluster.Builder.create(this, "EcsCluster").vpc(vpc).build();
 FargateTaskDefinition taskDefinition = FargateTaskDefinition.Builder.create(this, "TaskDef")
         .memoryLimitMiB(512)
         .cpu(256)
         .build();
 taskDefinition.addContainer("WebContainer", ContainerDefinitionOptions.builder()
         .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
         .build());
 Tags.of(taskDefinition).add("my-tag", "my-tag-value");
 ScheduledFargateTask scheduledFargateTask = ScheduledFargateTask.Builder.create(this, "ScheduledFargateTask")
         .cluster(cluster)
         .taskDefinition(taskDefinition)
         .schedule(Schedule.expression("rate(1 minute)"))
         .propagateTags(PropagatedTagSource.TASK_DEFINITION)
         .build();
 

Pass a list of tags for ScheduledFargateTask

You can pass a list of tags to be applied to a Fargate task directly. These tags are in addition to any tags that could be applied to the task definition and propagated using the propagateTags attribute.

 Vpc vpc = Vpc.Builder.create(this, "Vpc").maxAzs(1).build();
 Cluster cluster = Cluster.Builder.create(this, "EcsCluster").vpc(vpc).build();
 ScheduledFargateTask scheduledFargateTask = ScheduledFargateTask.Builder.create(this, "ScheduledFargateTask")
         .cluster(cluster)
         .scheduledFargateTaskImageOptions(ScheduledFargateTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .memoryLimitMiB(512)
                 .build())
         .schedule(Schedule.expression("rate(1 minute)"))
         .tags(List.of(Tag.builder()
                 .key("my-tag")
                 .value("my-tag-value")
                 .build()))
         .build();
 

Use custom ephemeral storage for ECS Fargate tasks

You can pass a custom ephemeral storage (21GiB - 200GiB) to ECS Fargate tasks on Fargate Platform Version 1.4.0 or later.

 Vpc vpc = Vpc.Builder.create(this, "Vpc").maxAzs(2).restrictDefaultSecurityGroup(false).build();
 Cluster cluster = Cluster.Builder.create(this, "FargateCluster").vpc(vpc).build();
 
 ApplicationLoadBalancedFargateService applicationLoadBalancedFargateService = ApplicationLoadBalancedFargateService.Builder.create(this, "ALBFargateServiceWithCustomEphemeralStorage")
         .cluster(cluster)
         .memoryLimitMiB(1024)
         .cpu(512)
         .ephemeralStorageGiB(21)
         .taskImageOptions(ApplicationLoadBalancedTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .build())
         .build();
 
 NetworkLoadBalancedFargateService networkLoadBalancedFargateService = NetworkLoadBalancedFargateService.Builder.create(this, "NLBFargateServiceWithCustomEphemeralStorage")
         .cluster(cluster)
         .memoryLimitMiB(1024)
         .cpu(512)
         .ephemeralStorageGiB(200)
         .taskImageOptions(NetworkLoadBalancedTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .build())
         .build();
 

Set securityGroups for NetworkLoadBalancedFargateService

 Vpc vpc;
 SecurityGroup securityGroup;
 
 NetworkLoadBalancedFargateService queueProcessingFargateService = NetworkLoadBalancedFargateService.Builder.create(this, "Service")
         .vpc(vpc)
         .memoryLimitMiB(512)
         .taskImageOptions(NetworkLoadBalancedTaskImageOptions.builder()
                 .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
                 .build())
         .securityGroups(List.of(securityGroup))
         .build();