Skip navigation links

Package software.amazon.awscdk.services.ecs

Amazon ECS Construct Library

See: Description

Package software.amazon.awscdk.services.ecs Description

Amazon ECS Construct Library

---

cfn-resources: Stable

cdk-constructs: Stable


This package contains constructs for working with Amazon Elastic Container Service (Amazon ECS).

Amazon Elastic Container Service (Amazon ECS) is a fully managed container orchestration service.

For further information on Amazon ECS, see the Amazon ECS documentation

The following example creates an Amazon ECS cluster, adds capacity to it, and runs a service on it:

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 import software.amazon.awscdk.services.ecs.*;
 
 // Create an ECS cluster
 Cluster cluster = new Cluster(this, "Cluster", new ClusterProps()
         .vpc(vpc));
 
 // Add capacity to it
 cluster.addCapacity("DefaultAutoScalingGroupCapacity", new AddCapacityOptions()
         .instanceType(new InstanceType("t2.xlarge"))
         .desiredCapacity(3));
 
 Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
 
 taskDefinition.addContainer("DefaultContainer", new ContainerDefinitionOptions()
         .image(ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
         .memoryLimitMiB(512));
 
 // Instantiate an Amazon ECS Service
 Ec2Service ecsService = new Ec2Service(this, "Service", new Ec2ServiceProps()
         .cluster(cluster)
         .taskDefinition(taskDefinition));
 

For a set of constructs defining common ECS architectural patterns, see the @aws-cdk/aws-ecs-patterns package.

Launch Types: AWS Fargate vs Amazon EC2

There are two sets of constructs in this library; one to run tasks on Amazon EC2 and one to run tasks on AWS Fargate.

Here are the main differences:

For more information on Amazon EC2 vs AWS Fargate, networking and ECS Anywhere see the AWS Documentation: AWS Fargate, Task Networking, ECS Anywhere

Clusters

A Cluster defines the infrastructure to run your tasks on. You can run many tasks on a single cluster.

The following code creates a cluster that can run AWS Fargate tasks:

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Object cluster = Cluster.Builder.create(this, "Cluster")
         .vpc(vpc)
         .build();
 

To use tasks with Amazon EC2 launch-type, you have to add capacity to the cluster in order for tasks to be scheduled on your instances. Typically, you add an AutoScalingGroup with instances running the latest Amazon ECS-optimized AMI to the cluster. There is a method to build and add such an AutoScalingGroup automatically, or you can supply a customized AutoScalingGroup that you construct yourself. It's possible to add multiple AutoScalingGroups with various instance types.

The following example creates an Amazon ECS cluster and adds capacity to it:

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Object cluster = Cluster.Builder.create(this, "Cluster")
         .vpc(vpc)
         .build();
 
 // Either add default capacity
 cluster.addCapacity("DefaultAutoScalingGroupCapacity", Map.of(
         "instanceType", new InstanceType("t2.xlarge"),
         "desiredCapacity", 3));
 
 // Or add customized capacity. Be sure to start the Amazon ECS-optimized AMI.
 Object autoScalingGroup = AutoScalingGroup.Builder.create(this, "ASG")
         .vpc(vpc)
         .instanceType(new InstanceType("t2.xlarge"))
         .machineImage(EcsOptimizedImage.amazonLinux())
         // Or use Amazon ECS-Optimized Amazon Linux 2 AMI
         // machineImage: EcsOptimizedImage.amazonLinux2(),
         .desiredCapacity(3)
         .build();
 
 cluster.addAutoScalingGroup(autoScalingGroup);
 

If you omit the property vpc, the construct will create a new VPC with two AZs.

By default, all machine images will auto-update to the latest version on each deployment, causing a replacement of the instances in your AutoScalingGroup if the AMI has been updated since the last deployment.

If task draining is enabled, ECS will transparently reschedule tasks on to the new instances before terminating your old instances. If you have disabled task draining, the tasks will be terminated along with the instance. To prevent that, you can pick a non-updating AMI by passing cacheInContext: true, but be sure to periodically update to the latest AMI manually by using the CDK CLI context management commands:

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Object autoScalingGroup = AutoScalingGroup.Builder.create(this, "ASG")
         // ...
         .machineImage(EcsOptimizedImage.amazonLinux(Map.of("cacheInContext", true)))
         .build();
 

Bottlerocket

Bottlerocket is a Linux-based open source operating system that is purpose-built by AWS for running containers. You can launch Amazon ECS container instances with the Bottlerocket AMI.

The following example will create a capacity with self-managed Amazon EC2 capacity of 2 c5.large Linux instances running with Bottlerocket AMI.

The following example adds Bottlerocket capacity to the cluster:

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 cluster.addCapacity("bottlerocket-asg", Map.of(
         "minCapacity", 2,
         "instanceType", new InstanceType("c5.large"),
         "machineImage", new BottleRocketImage()));
 

ARM64 (Graviton) Instances

To launch instances with ARM64 hardware, you can use the Amazon ECS-optimized Amazon Linux 2 (arm64) AMI. Based on Amazon Linux 2, this AMI is recommended for use when launching your EC2 instances that are powered by Arm-based AWS Graviton Processors.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 cluster.addCapacity("graviton-cluster", Map.of(
         "minCapacity", 2,
         "instanceType", new InstanceType("c6g.large"),
         "machineImage", ecs.EcsOptimizedImage.amazonLinux2(ecs.AmiHardwareType.getARM())));
 

Bottlerocket is also supported:

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 cluster.addCapacity("graviton-cluster", Map.of(
         "minCapacity", 2,
         "instanceType", new InstanceType("c6g.large"),
         "machineImage", ecs.MachineImageType.getBOTTLEROCKET()));
 

Spot Instances

To add spot instances into the cluster, you must specify the spotPrice in the ecs.AddCapacityOptions and optionally enable the spotInstanceDraining property.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 // Add an AutoScalingGroup with spot instances to the existing cluster
 cluster.addCapacity("AsgSpot", Map.of(
         "maxCapacity", 2,
         "minCapacity", 2,
         "desiredCapacity", 2,
         "instanceType", new InstanceType("c5.xlarge"),
         "spotPrice", "0.0735",
         // Enable the Automated Spot Draining support for Amazon ECS
         "spotInstanceDraining", true));
 

SNS Topic Encryption

When the ecs.AddCapacityOptions that you provide has a non-zero taskDrainTime (the default) then an SNS topic and Lambda are created to ensure that the cluster's instances have been properly drained of tasks before terminating. The SNS Topic is sent the instance-terminating lifecycle event from the AutoScalingGroup, and the Lambda acts on that event. If you wish to engage server-side encryption for this SNS Topic then you may do so by providing a KMS key for the topicEncryptionKey property of ecs.AddCapacityOptions.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 // Given
 Object key = kms.Key(...);
 // Then, use that key to encrypt the lifecycle-event SNS Topic.
 cluster.addCapacity("ASGEncryptedSNS", Map.of(
         "instanceType", new InstanceType("t2.xlarge"),
         "desiredCapacity", 3,
         "topicEncryptionKey", key));
 

Task definitions

A task definition describes what a single copy of a task should look like. A task definition has one or more containers; typically, it has one main container (the default container is the first one that's added to the task definition, and it is marked essential) and optionally some supporting containers which are used to support the main container, doings things like upload logs or metrics to monitoring services.

To run a task or service with Amazon EC2 launch type, use the Ec2TaskDefinition. For AWS Fargate tasks/services, use the FargateTaskDefinition. For AWS ECS Anywhere use the ExternalTaskDefinition. These classes provide simplified APIs that only contain properties relevant for each specific launch type.

For a FargateTaskDefinition, specify the task size (memoryLimitMiB and cpu):

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Object fargateTaskDefinition = FargateTaskDefinition.Builder.create(this, "TaskDef")
         .memoryLimitMiB(512)
         .cpu(256)
         .build();
 

On Fargate Platform Version 1.4.0 or later, you may specify up to 200GiB of ephemeral storage:

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Object fargateTaskDefinition = FargateTaskDefinition.Builder.create(this, "TaskDef")
         .memoryLimitMiB(512)
         .cpu(256)
         .ephemeralStorageGiB(100)
         .build();
 

To add containers to a task definition, call addContainer():

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Object container = fargateTaskDefinition.addContainer("WebContainer", Map.of(
         // Use an image from DockerHub
         "image", ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample")));
 

For a Ec2TaskDefinition:

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Object ec2TaskDefinition = Ec2TaskDefinition.Builder.create(this, "TaskDef")
         .networkMode(NetworkMode.getBRIDGE())
         .build();
 
 Object container = ec2TaskDefinition.addContainer("WebContainer", Map.of(
         // Use an image from DockerHub
         "image", ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
         "memoryLimitMiB", 1024));
 

For an ExternalTaskDefinition:

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Object externalTaskDefinition = new ExternalTaskDefinition(this, "TaskDef");
 
 Object container = externalTaskDefinition.addContainer("WebContainer", Map.of(
         // Use an image from DockerHub
         "image", ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
         "memoryLimitMiB", 1024));
 

You can specify container properties when you add them to the task definition, or with various methods, e.g.:

To add a port mapping when adding a container to the task definition, specify the portMappings option:

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 taskDefinition.addContainer("WebContainer", Map.of(
         "image", ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
         "memoryLimitMiB", 1024,
         "portMappings", asList(Map.of("containerPort", 3000))));
 

To add port mappings directly to a container definition, call addPortMappings():

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 container.addPortMappings(Map.of(
         "containerPort", 3000));
 

To add data volumes to a task definition, call addVolume():

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 __object volume = Map.of(
         // Use an Elastic FileSystem
         "name", "mydatavolume",
         "efsVolumeConfiguration", ecs.EfsVolumeConfiguration(Map.of(
                 "fileSystemId", "EFS")));
 
 Object container = fargateTaskDefinition.addVolume("mydatavolume");
 

Note: ECS Anywhere doesn't support volume attachments in the task definition.

To use a TaskDefinition that can be used with either Amazon EC2 or AWS Fargate launch types, use the TaskDefinition construct.

When creating a task definition you have to specify what kind of tasks you intend to run: Amazon EC2, AWS Fargate, or both. The following example uses both:

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Object taskDefinition = TaskDefinition.Builder.create(this, "TaskDef")
         .memoryMiB("512")
         .cpu("256")
         .networkMode(NetworkMode.getAWS_VPC())
         .compatibility(ecs.Compatibility.getEC2_AND_FARGATE())
         .build();
 

Images

Images supply the software that runs inside the container. Images can be obtained from either DockerHub or from ECR repositories, built directly from a local Dockerfile, or use an existing tarball.

Environment variables

To pass environment variables to the container, you can use the environment, environmentFiles, and secrets props.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 taskDefinition.addContainer("container", Map.of(
         "image", ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
         "memoryLimitMiB", 1024,
         "environment", Map.of(// clear text, not for sensitive data
                 "STAGE", "prod"),
         "environmentFiles", asList(ecs.EnvironmentFile.fromAsset("./demo-env-file.env"), ecs.EnvironmentFile.fromBucket(s3Bucket, "assets/demo-env-file.env")),
         "secrets", Map.of(// Retrieved from AWS Secrets Manager or AWS Systems Manager Parameter Store at container start-up.
                 "SECRET", ecs.Secret.fromSecretsManager(secret),
                 "DB_PASSWORD", ecs.Secret.fromSecretsManager(dbSecret, "password"), // Reference a specific JSON field, (requires platform version 1.4.0 or later for Fargate tasks)
                 "PARAMETER", ecs.Secret.fromSsmParameter(parameter))));
 

The task execution role is automatically granted read permissions on the secrets/parameters. Support for environment files is restricted to the EC2 launch type for files hosted on S3. Further details provided in the AWS documentation about specifying environment variables.

Service

A Service instantiates a TaskDefinition on a Cluster a given number of times, optionally associating them with a load balancer. If a task fails, Amazon ECS automatically restarts the task.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Object taskDefinition;
 
 Object service = FargateService.Builder.create(this, "Service")
         .cluster(cluster)
         .taskDefinition(taskDefinition)
         .desiredCount(5)
         .build();
 

ECS Anywhere service definition looks like:

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Object taskDefinition;
 
 Object service = ExternalService.Builder.create(this, "Service")
         .cluster(cluster)
         .taskDefinition(taskDefinition)
         .desiredCount(5)
         .build();
 

Services by default will create a security group if not provided. If you'd like to specify which security groups to use you can override the securityGroups property.

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.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Object service = FargateService.Builder.create(stack, "Service")
         .cluster(cluster)
         .taskDefinition(taskDefinition)
         .circuitBreaker(Map.of("rollback", true))
         .build();
 

Note: ECS Anywhere doesn't support deployment circuit breakers and rollback.

Include an application/network load balancer

Services are load balancing targets and can be added to a target group, which will be attached to an application/network load balancers:

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 import software.amazon.awscdk.services.elasticloadbalancingv2.*;
 
 Object service = FargateService.Builder.create(this, "Service").build();
 
 ApplicationLoadBalancer lb = new ApplicationLoadBalancer(this, "LB", new ApplicationLoadBalancerProps().vpc(vpc).internetFacing(true));
 ApplicationListener listener = lb.addListener("Listener", new BaseApplicationListenerProps().port(80));
 ApplicationTargetGroup targetGroup1 = listener.addTargets("ECS1", new AddApplicationTargetsProps()
         .port(80)
         .targets(asList(service)));
 ApplicationTargetGroup targetGroup2 = listener.addTargets("ECS2", new AddApplicationTargetsProps()
         .port(80)
         .targets(asList(service.loadBalancerTarget(Map.of(
                 "containerName", "MyContainer",
                 "containerPort", 8080)))));
 

Note: ECS Anywhere doesn't support application/network load balancers.

Note that in the example above, the default service only allows you to register the first essential container or the first mapped port on the container as a target and add it to a new target group. To have more control over which container and port to register as targets, you can use service.loadBalancerTarget() to return a load balancing target for a specific container and port.

Alternatively, you can also create all load balancer targets to be registered in this service, add them to target groups, and attach target groups to listeners accordingly.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 import software.amazon.awscdk.services.elasticloadbalancingv2.*;
 
 Object service = FargateService.Builder.create(this, "Service").build();
 
 ApplicationLoadBalancer lb = new ApplicationLoadBalancer(this, "LB", new ApplicationLoadBalancerProps().vpc(vpc).internetFacing(true));
 ApplicationListener listener = lb.addListener("Listener", new BaseApplicationListenerProps().port(80));
 service.registerLoadBalancerTargets(Map.of(
         "containerName", "web",
         "containerPort", 80,
         "newTargetGroupId", "ECS",
         "listener", ecs.ListenerConfig.applicationListener(listener, Map.of(
                 "protocol", elbv2.ApplicationProtocol.getHTTPS()))));
 

Using a Load Balancer from a different Stack

If you want to put your Load Balancer and the Service 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 service stack, or an empty TargetGroup in the load balancer stack that you attach your service to.

See the ecs/cross-stack-load-balancer example for the alternatives.

Include a classic load balancer

Services can also be directly attached to a classic load balancer as targets:

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 import software.amazon.awscdk.services.elasticloadbalancing.*;
 
 Object service = Ec2Service.Builder.create(this, "Service").build();
 
 LoadBalancer lb = new LoadBalancer(stack, "LB", new LoadBalancerProps().vpc(vpc));
 lb.addListener(new LoadBalancerListener().externalPort(80));
 lb.addTarget(service);
 

Similarly, if you want to have more control over load balancer targeting:

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 import software.amazon.awscdk.services.elasticloadbalancing.*;
 
 Object service = Ec2Service.Builder.create(this, "Service").build();
 
 LoadBalancer lb = new LoadBalancer(stack, "LB", new LoadBalancerProps().vpc(vpc));
 lb.addListener(new LoadBalancerListener().externalPort(80));
 lb.addTarget(service.loadBalancerTarget(Map.of(
         "containerName", "MyContainer",
         "containerPort", 80)));
 

There are two higher-level constructs available which include a load balancer for you that can be found in the aws-ecs-patterns module:

Task Auto-Scaling

You can configure the task count of a service to match demand. Task auto-scaling is configured by calling autoScaleTaskCount():

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Object scaling = service.autoScaleTaskCount(Map.of("maxCapacity", 10));
 scaling.scaleOnCpuUtilization("CpuScaling", Map.of(
         "targetUtilizationPercent", 50));
 
 scaling.scaleOnRequestCount("RequestScaling", Map.of(
         "requestsPerTarget", 10000,
         "targetGroup", target));
 

Task auto-scaling is powered by Application Auto-Scaling. See that section for details.

Integration with CloudWatch Events

To start an Amazon ECS task on an Amazon EC2-backed Cluster, instantiate an @aws-cdk/aws-events-targets.EcsTask instead of an Ec2Service:

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 import software.amazon.awscdk.services.events.targets.*;
 
 // Create a Task Definition for the container to start
 Object taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
 taskDefinition.addContainer("TheContainer", Map.of(
         "image", ecs.ContainerImage.fromAsset(path.resolve(__dirname, "..", "eventhandler-image")),
         "memoryLimitMiB", 256,
         "logging", AwsLogDriver.Builder.create().streamPrefix("EventDemo").mode(AwsLogDriverMode.getNON_BLOCKING()).build()));
 
 // An Rule that describes the event trigger (in this case a scheduled run)
 Object rule = Rule.Builder.create(this, "Rule")
         .schedule(events.Schedule.expression("rate(1 min)"))
         .build();
 
 // Pass an environment variable to the container 'TheContainer' in the task
 rule.addTarget(new EcsTask(new EcsTaskProps()
         .cluster(cluster)
         .taskDefinition(taskDefinition)
         .taskCount(1)
         .containerOverrides(asList(new ContainerOverride()
                 .containerName("TheContainer")
                 .environment(asList(new TaskEnvironmentVariable()
                         .name("I_WAS_TRIGGERED")
                         .value("From CloudWatch Events")))))));
 

Log Drivers

Currently Supported Log Drivers:

awslogs Log Driver

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 // Create a Task Definition for the container to start
 Object taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
 taskDefinition.addContainer("TheContainer", Map.of(
         "image", ecs.ContainerImage.fromRegistry("example-image"),
         "memoryLimitMiB", 256,
         "logging", ecs.LogDrivers.awsLogs(Map.of("streamPrefix", "EventDemo"))));
 

fluentd Log Driver

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 // Create a Task Definition for the container to start
 Object taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
 taskDefinition.addContainer("TheContainer", Map.of(
         "image", ecs.ContainerImage.fromRegistry("example-image"),
         "memoryLimitMiB", 256,
         "logging", ecs.LogDrivers.fluentd()));
 

gelf Log Driver

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 // Create a Task Definition for the container to start
 Object taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
 taskDefinition.addContainer("TheContainer", Map.of(
         "image", ecs.ContainerImage.fromRegistry("example-image"),
         "memoryLimitMiB", 256,
         "logging", ecs.LogDrivers.gelf(Map.of("address", "my-gelf-address"))));
 

journald Log Driver

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 // Create a Task Definition for the container to start
 Object taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
 taskDefinition.addContainer("TheContainer", Map.of(
         "image", ecs.ContainerImage.fromRegistry("example-image"),
         "memoryLimitMiB", 256,
         "logging", ecs.LogDrivers.journald()));
 

json-file Log Driver

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 // Create a Task Definition for the container to start
 Object taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
 taskDefinition.addContainer("TheContainer", Map.of(
         "image", ecs.ContainerImage.fromRegistry("example-image"),
         "memoryLimitMiB", 256,
         "logging", ecs.LogDrivers.jsonFile()));
 

splunk Log Driver

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 // Create a Task Definition for the container to start
 Object taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
 taskDefinition.addContainer("TheContainer", Map.of(
         "image", ecs.ContainerImage.fromRegistry("example-image"),
         "memoryLimitMiB", 256,
         "logging", ecs.LogDrivers.splunk(Map.of(
                 "secretToken", cdk.SecretValue.secretsManager("my-splunk-token"),
                 "url", "my-splunk-url"))));
 

syslog Log Driver

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 // Create a Task Definition for the container to start
 Object taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
 taskDefinition.addContainer("TheContainer", Map.of(
         "image", ecs.ContainerImage.fromRegistry("example-image"),
         "memoryLimitMiB", 256,
         "logging", ecs.LogDrivers.syslog()));
 

firelens Log Driver

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 // Create a Task Definition for the container to start
 Object taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
 taskDefinition.addContainer("TheContainer", Map.of(
         "image", ecs.ContainerImage.fromRegistry("example-image"),
         "memoryLimitMiB", 256,
         "logging", ecs.LogDrivers.firelens(Map.of(
                 "options", Map.of(
                         "Name", "firehose",
                         "region", "us-west-2",
                         "delivery_stream", "my-stream")))));
 

To pass secrets to the log configuration, use the secretOptions property of the log configuration. The task execution role is automatically granted read permissions on the secrets/parameters.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Object taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
 taskDefinition.addContainer("TheContainer", Map.of(
         "image", ecs.ContainerImage.fromRegistry("example-image"),
         "memoryLimitMiB", 256,
         "logging", ecs.LogDrivers.firelens(Map.of(
                 "options", Map.of(),
                 "secretOptions", Map.of(// Retrieved from AWS Secrets Manager or AWS Systems Manager Parameter Store
                         "apikey", ecs.Secret.fromSecretsManager(secret),
                         "host", ecs.Secret.fromSsmParameter(parameter))))));
 

Generic Log Driver

A generic log driver object exists to provide a lower level abstraction of the log driver configuration.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 // Create a Task Definition for the container to start
 Object taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
 taskDefinition.addContainer("TheContainer", Map.of(
         "image", ecs.ContainerImage.fromRegistry("example-image"),
         "memoryLimitMiB", 256,
         "logging", GenericLogDriver.Builder.create()
                 .logDriver("fluentd")
                 .options(Map.of(
                         "tag", "example-tag"))
                 .build()));
 

CloudMap Service Discovery

To register your ECS service with a CloudMap Service Registry, you may add the cloudMapOptions property to your service:

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Object service = Ec2Service.Builder.create(stack, "Service")
         .cluster(cluster)
         .taskDefinition(taskDefinition)
         .cloudMapOptions(Map.of(
                 // Create A records - useful for AWSVPC network mode.
                 "dnsRecordType", cloudmap.DnsRecordType.getA()))
         .build();
 

With bridge or host network modes, only SRV DNS record types are supported. By default, SRV DNS record types will target the default container and default port. However, you may target a different container and port on the same ECS task:

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 // Add a container to the task definition
 Object specificContainer = taskDefinition.addContainer(...);
 
 // Add a port mapping
 specificContainer.addPortMappings(Map.of(
         "containerPort", 7600,
         "protocol", ecs.Protocol.getTCP()));
 
 Ec2Service.Builder.create(stack, "Service")
         .cluster(cluster)
         .taskDefinition(taskDefinition)
         .cloudMapOptions(Map.of(
                 // Create SRV records - useful for bridge networking
                 "dnsRecordType", cloudmap.DnsRecordType.getSRV(),
                 // Targets port TCP port 7600 `specificContainer`
                 "container", specificContainer,
                 "containerPort", 7600))
         .build();
 

Associate With a Specific CloudMap Service

You may associate an ECS service with a specific CloudMap service. To do this, use the service's associateCloudMapService method:

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Object cloudMapService = new Service(...);
 Object ecsService = new FargateService(...);
 
 ecsService.associateCloudMapService(Map.of(
         "service", cloudMapService));
 

Capacity Providers

There are two major families of Capacity Providers: AWS Fargate (including Fargate Spot) and EC2 Auto Scaling Group Capacity Providers. Both are supported.

Fargate Capacity Providers

To enable Fargate capacity providers, you can either set enableFargateCapacityProviders to true when creating your cluster, or by invoking the enableFargateCapacityProviders() method after creating your cluster. This will add both FARGATE and FARGATE_SPOT as available capacity providers on your cluster.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Object cluster = Cluster.Builder.create(stack, "FargateCPCluster")
         .vpc(vpc)
         .enableFargateCapacityProviders(true)
         .build();
 
 Object taskDefinition = new FargateTaskDefinition(stack, "TaskDef");
 
 taskDefinition.addContainer("web", Map.of(
         "image", ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample")));
 
 FargateService.Builder.create(stack, "FargateService")
         .cluster(cluster)
         .taskDefinition(taskDefinition)
         .capacityProviderStrategies(asList(Map.of(
                 "capacityProvider", "FARGATE_SPOT",
                 "weight", 2), Map.of(
                 "capacityProvider", "FARGATE",
                 "weight", 1)))
         .build();
 

Auto Scaling Group Capacity Providers

To add an Auto Scaling Group Capacity Provider, first create an EC2 Auto Scaling Group. Then, create an AsgCapacityProvider and pass the Auto Scaling Group to it in the constructor. Then add the Capacity Provider to the cluster. Finally, you can refer to the Provider by its name in your service's or task's Capacity Provider strategy.

By default, an Auto Scaling Group Capacity Provider will manage the Auto Scaling Group's size for you. It will also enable managed termination protection, in order to prevent EC2 Auto Scaling from terminating EC2 instances that have tasks running on them. If you want to disable this behavior, set both enableManagedScaling to and enableManagedTerminationProtection to false.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Object cluster = Cluster.Builder.create(stack, "Cluster")
         .vpc(vpc)
         .build();
 
 Object autoScalingGroup = AutoScalingGroup.Builder.create(stack, "ASG")
         .vpc(vpc)
         .instanceType(new InstanceType("t2.micro"))
         .machineImage(ecs.EcsOptimizedImage.amazonLinux2())
         .minCapacity(0)
         .maxCapacity(100)
         .build();
 
 Object capacityProvider = AsgCapacityProvider.Builder.create(stack, "AsgCapacityProvider")
         .autoScalingGroup(autoScalingGroup)
         .build();
 cluster.addAsgCapacityProvider(capacityProvider);
 
 Object taskDefinition = new Ec2TaskDefinition(stack, "TaskDef");
 
 taskDefinition.addContainer("web", Map.of(
         "image", ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
         "memoryReservationMiB", 256));
 
 Ec2Service.Builder.create(stack, "EC2Service")
         .cluster(cluster)
         .taskDefinition(taskDefinition)
         .capacityProviderStrategies(asList(Map.of(
                 "capacityProvider", capacityProvider.getCapacityProviderName(),
                 "weight", 1)))
         .build();
 

Elastic Inference Accelerators

Currently, this feature is only supported for services with EC2 launch types.

To add elastic inference accelerators to your EC2 instance, first add inferenceAccelerators field to the Ec2TaskDefinition and set the deviceName and deviceType properties.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Array inferenceAccelerators = asList(Map.of(
         "deviceName", "device1",
         "deviceType", "eia2.medium"));
 
 Object taskDefinition = Ec2TaskDefinition.Builder.create(stack, "Ec2TaskDef")
         .inferenceAccelerators(inferenceAccelerators)
         .build();
 

To enable using the inference accelerators in the containers, add inferenceAcceleratorResources field and set it to a list of device names used for the inference accelerators. Each value in the list should match a DeviceName for an InferenceAccelerator specified in the task definition.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Array inferenceAcceleratorResources = asList("device1");
 
 taskDefinition.addContainer("cont", Map.of(
         "image", ecs.ContainerImage.fromRegistry("test"),
         "memoryLimitMiB", 1024,
         "inferenceAcceleratorResources", inferenceAcceleratorResources));
 

ECS Exec command

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.

To enable the ECS Exec feature for your containers, set the boolean flag enableExecuteCommand to true in your Ec2Service or FargateService.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Object service = Ec2Service.Builder.create(stack, "Service")
         .cluster(cluster)
         .taskDefinition(taskDefinition)
         .enableExecuteCommand(true)
         .build();
 

Enabling logging

You can enable sending logs of your execute session commands to a CloudWatch log group or S3 bucket by configuring the executeCommandConfiguration property for your cluster. The default configuration will send the logs to the CloudWatch Logs using the awslogs log driver that is configured in your task definition. Please note, when using your own logConfiguration the log group or S3 Bucket specified must already be created.

To encrypt data using your own KMS Customer Key (CMK), you must create a CMK and provide the key in the kmsKey field of the executeCommandConfiguration. To use this key for encrypting CloudWatch log data or S3 bucket, make sure to associate the key to these resources on creation.

 // Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
 Object kmsKey = new Key(stack, "KmsKey");
 
 // Pass the KMS key in the `encryptionKey` field to associate the key to the log group
 Object logGroup = LogGroup.Builder.create(stack, "LogGroup")
         .encryptionKey(kmsKey)
         .build();
 
 // Pass the KMS key in the `encryptionKey` field to associate the key to the S3 bucket
 Bucket execBucket = new Bucket(stack, "EcsExecBucket", new BucketProps()
         .encryptionKey(kmsKey));
 
 Object cluster = Cluster.Builder.create(stack, "Cluster")
         .vpc(vpc)
         .executeCommandConfiguration(Map.of(
                 "kmsKey", kmsKey,
                 "logConfiguration", Map.of(
                         "cloudWatchLogGroup", logGroup,
                         "cloudWatchEncryptionEnabled", true,
                         "s3Bucket", execBucket,
                         "s3EncryptionEnabled", true,
                         "s3KeyPrefix", "exec-command-output"),
                 "logging", ecs.ExecuteCommandLogging.getOVERRIDE()))
         .build();
 
Skip navigation links