Package software.amazon.awscdk.services.ecs
Amazon ECS Construct Library
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:
Vpc vpc;
// Create an ECS cluster
Cluster cluster = Cluster.Builder.create(this, "Cluster").vpc(vpc).build();
// Add capacity to it
cluster.addCapacity("DefaultAutoScalingGroupCapacity", AddCapacityOptions.builder()
.instanceType(new InstanceType("t2.xlarge"))
.desiredCapacity(3)
.build());
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("DefaultContainer", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
.memoryLimitMiB(512)
.build());
// Instantiate an Amazon ECS Service
Ec2Service ecsService = Ec2Service.Builder.create(this, "Service")
.cluster(cluster)
.taskDefinition(taskDefinition)
.minHealthyPercent(100)
.build();
For a set of constructs defining common ECS architectural patterns, see the aws-cdk-lib/aws-ecs-patterns package.
Launch Types: AWS Fargate vs Amazon EC2 vs AWS ECS Anywhere
There are three sets of constructs in this library:
- Use the
Ec2TaskDefinitionandEc2Serviceconstructs to run tasks on Amazon EC2 instances running in your account. - Use the
FargateTaskDefinitionandFargateServiceconstructs to run tasks on instances that are managed for you by AWS. - Use the
ExternalTaskDefinitionandExternalServiceconstructs to run AWS ECS Anywhere tasks on self-managed infrastructure.
Here are the main differences:
- Amazon EC2: instances are under your control. Complete control of task to host allocation. Required to specify at least a memory reservation or limit for every container. Can use Host, Bridge and AwsVpc networking modes. Can attach Classic Load Balancer. Can share volumes between container and host.
- AWS Fargate: tasks run on AWS-managed instances, AWS manages task to host allocation for you. Requires specification of memory and cpu sizes at the taskdefinition level. Only supports AwsVpc networking modes and Application/Network Load Balancers. Only the AWS log driver is supported. Many host features are not supported such as adding kernel capabilities and mounting host devices/volumes inside the container.
- AWS ECS Anywhere: tasks are run and managed by AWS ECS Anywhere on infrastructure owned by the customer. Bridge, Host and None networking modes are supported. Does not support autoscaling, load balancing, cloudmap or attachment of volumes.
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:
Vpc vpc;
Cluster cluster = Cluster.Builder.create(this, "Cluster")
.vpc(vpc)
.build();
By default, storage is encrypted with AWS-managed key. You can specify customer-managed key using:
Key key;
Cluster cluster = Cluster.Builder.create(this, "Cluster")
.managedStorageConfiguration(ManagedStorageConfiguration.builder()
.fargateEphemeralStorageKmsKey(key)
.kmsKey(key)
.build())
.build();
The following code imports an existing cluster using the ARN which can be used to import an Amazon ECS service either EC2 or Fargate.
String clusterArn = "arn:aws:ecs:us-east-1:012345678910:cluster/clusterName"; ICluster cluster = Cluster.fromClusterArn(this, "Cluster", clusterArn);
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:
Vpc vpc;
Cluster cluster = Cluster.Builder.create(this, "Cluster")
.vpc(vpc)
.build();
// Either add default capacity
cluster.addCapacity("DefaultAutoScalingGroupCapacity", AddCapacityOptions.builder()
.instanceType(new InstanceType("t2.xlarge"))
.desiredCapacity(3)
.build());
// Or add customized capacity. Be sure to start the Amazon ECS-optimized AMI.
AutoScalingGroup 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();
AsgCapacityProvider capacityProvider = AsgCapacityProvider.Builder.create(this, "AsgCapacityProvider")
.autoScalingGroup(autoScalingGroup)
.build();
cluster.addAsgCapacityProvider(capacityProvider);
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:
Vpc vpc;
AutoScalingGroup autoScalingGroup = AutoScalingGroup.Builder.create(this, "ASG")
.machineImage(EcsOptimizedImage.amazonLinux(EcsOptimizedImageOptions.builder().cachedInContext(true).build()))
.vpc(vpc)
.instanceType(new InstanceType("t2.micro"))
.build();
To customize the cache key, use the additionalCacheKey parameter.
This allows you to have multiple lookups with the same parameters
cache their values separately. This can be useful if you want to
scope the context variable to a construct (ie, using additionalCacheKey: this.node.path),
so that if the value in the cache needs to be updated, it does not need to be updated
for all constructs at the same time.
Vpc vpc;
AutoScalingGroup autoScalingGroup = AutoScalingGroup.Builder.create(this, "ASG")
.machineImage(EcsOptimizedImage.amazonLinux(EcsOptimizedImageOptions.builder().cachedInContext(true).additionalCacheKey(this.node.getPath()).build()))
.vpc(vpc)
.instanceType(new InstanceType("t2.micro"))
.build();
To use LaunchTemplate with AsgCapacityProvider, make sure to specify the userData in the LaunchTemplate:
Vpc vpc;
LaunchTemplate launchTemplate = LaunchTemplate.Builder.create(this, "ASG-LaunchTemplate")
.instanceType(new InstanceType("t3.medium"))
.machineImage(EcsOptimizedImage.amazonLinux2())
.userData(UserData.forLinux())
.build();
AutoScalingGroup autoScalingGroup = AutoScalingGroup.Builder.create(this, "ASG")
.vpc(vpc)
.mixedInstancesPolicy(MixedInstancesPolicy.builder()
.instancesDistribution(InstancesDistribution.builder()
.onDemandPercentageAboveBaseCapacity(50)
.build())
.launchTemplate(launchTemplate)
.build())
.build();
Cluster cluster = Cluster.Builder.create(this, "Cluster").vpc(vpc).build();
AsgCapacityProvider capacityProvider = AsgCapacityProvider.Builder.create(this, "AsgCapacityProvider")
.autoScalingGroup(autoScalingGroup)
.machineImageType(MachineImageType.AMAZON_LINUX_2)
.build();
cluster.addAsgCapacityProvider(capacityProvider);
The following code retrieve the Amazon Resource Names (ARNs) of tasks that are a part of a specified ECS cluster. It's useful when you want to grant permissions to a task to access other AWS resources.
Cluster cluster;
TaskDefinition taskDefinition;
String taskARNs = cluster.arnForTasks("*"); // arn:aws:ecs:<region>:<regionId>:task/<clusterName>/*
// Grant the task permission to access other AWS resources
taskDefinition.addToTaskRolePolicy(
PolicyStatement.Builder.create()
.actions(List.of("ecs:UpdateTaskProtection"))
.resources(List.of(taskARNs))
.build());
To manage task protection settings in an ECS cluster, you can use the grantTaskProtection method.
This method grants the ecs:UpdateTaskProtection permission to a specified IAM entity.
// Assume 'cluster' is an instance of ecs.Cluster Cluster cluster; Role taskRole; // Grant ECS Task Protection permissions to the role // Now 'taskRole' has the 'ecs:UpdateTaskProtection' permission on all tasks in the cluster cluster.grantTaskProtection(taskRole);
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:
Cluster cluster;
cluster.addCapacity("bottlerocket-asg", AddCapacityOptions.builder()
.minCapacity(2)
.instanceType(new InstanceType("c5.large"))
.machineImage(new BottleRocketImage())
.build());
You can also specify an NVIDIA-compatible AMI such as in this example:
Cluster cluster;
cluster.addCapacity("bottlerocket-asg", AddCapacityOptions.builder()
.instanceType(new InstanceType("p3.2xlarge"))
.machineImage(BottleRocketImage.Builder.create()
.variant(BottlerocketEcsVariant.AWS_ECS_2_NVIDIA)
.build())
.build());
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.
Cluster cluster;
cluster.addCapacity("graviton-cluster", AddCapacityOptions.builder()
.minCapacity(2)
.instanceType(new InstanceType("c6g.large"))
.machineImage(EcsOptimizedImage.amazonLinux2(AmiHardwareType.ARM))
.build());
Bottlerocket is also supported:
Cluster cluster;
cluster.addCapacity("graviton-cluster", AddCapacityOptions.builder()
.minCapacity(2)
.instanceType(new InstanceType("c6g.large"))
.machineImageType(MachineImageType.BOTTLEROCKET)
.build());
Amazon Linux 2 (Neuron) Instances
To launch Amazon EC2 Inf1, Trn1 or Inf2 instances, you can use the Amazon ECS optimized Amazon Linux 2 (Neuron) AMI. It comes pre-configured with AWS Inferentia and AWS Trainium drivers and the AWS Neuron runtime for Docker which makes running machine learning inference workloads easier on Amazon ECS.
Cluster cluster;
cluster.addCapacity("neuron-cluster", AddCapacityOptions.builder()
.minCapacity(2)
.instanceType(new InstanceType("inf1.xlarge"))
.machineImage(EcsOptimizedImage.amazonLinux2(AmiHardwareType.NEURON))
.build());
Spot Instances
To add spot instances into the cluster, you must specify the spotPrice in the ecs.AddCapacityOptions and optionally enable the spotInstanceDraining property.
Cluster cluster;
// Add an AutoScalingGroup with spot instances to the existing cluster
cluster.addCapacity("AsgSpot", AddCapacityOptions.builder()
.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)
.build());
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.
// Given
Cluster cluster;
Key key;
// Then, use that key to encrypt the lifecycle-event SNS Topic.
cluster.addCapacity("ASGEncryptedSNS", AddCapacityOptions.builder()
.instanceType(new InstanceType("t2.xlarge"))
.desiredCapacity(3)
.topicEncryptionKey(key)
.build());
Container Insights
On a cluster, CloudWatch Container Insights can be enabled by setting the containerInsightsV2 property. Container Insights
can be disabled, enabled, or enhanced.
Cluster cluster = Cluster.Builder.create(this, "Cluster")
.containerInsightsV2(ContainerInsights.ENHANCED)
.build();
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):
FargateTaskDefinition 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:
FargateTaskDefinition fargateTaskDefinition = FargateTaskDefinition.Builder.create(this, "TaskDef")
.memoryLimitMiB(512)
.cpu(256)
.ephemeralStorageGiB(100)
.build();
To specify the process namespace to use for the containers in the task, use the pidMode property:
FargateTaskDefinition fargateTaskDefinition = FargateTaskDefinition.Builder.create(this, "TaskDef")
.runtimePlatform(RuntimePlatform.builder()
.operatingSystemFamily(OperatingSystemFamily.LINUX)
.cpuArchitecture(CpuArchitecture.ARM64)
.build())
.memoryLimitMiB(512)
.cpu(256)
.pidMode(PidMode.TASK)
.build();
Note: pidMode is only supported for tasks that are hosted on AWS Fargate if the tasks are using platform version 1.4.0
or later (Linux). Only the task option is supported for Linux containers. pidMode isn't supported for Windows containers on Fargate.
If pidMode is specified for a Fargate task, then runtimePlatform.operatingSystemFamily must also be specified.
To add containers to a task definition, call addContainer():
FargateTaskDefinition fargateTaskDefinition = FargateTaskDefinition.Builder.create(this, "TaskDef")
.memoryLimitMiB(512)
.cpu(256)
.build();
ContainerDefinition container = fargateTaskDefinition.addContainer("WebContainer", ContainerDefinitionOptions.builder()
// Use an image from DockerHub
.image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
.build());
For an Ec2TaskDefinition:
Ec2TaskDefinition ec2TaskDefinition = Ec2TaskDefinition.Builder.create(this, "TaskDef")
.networkMode(NetworkMode.BRIDGE)
.build();
ContainerDefinition container = ec2TaskDefinition.addContainer("WebContainer", ContainerDefinitionOptions.builder()
// Use an image from DockerHub
.image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
.memoryLimitMiB(1024)
.build());
For an ExternalTaskDefinition:
ExternalTaskDefinition externalTaskDefinition = new ExternalTaskDefinition(this, "TaskDef");
ContainerDefinition container = externalTaskDefinition.addContainer("WebContainer", ContainerDefinitionOptions.builder()
// Use an image from DockerHub
.image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
.memoryLimitMiB(1024)
.build());
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:
TaskDefinition taskDefinition;
taskDefinition.addContainer("WebContainer", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
.memoryLimitMiB(1024)
.portMappings(List.of(PortMapping.builder().containerPort(3000).build()))
.build());
To add port mappings directly to a container definition, call addPortMappings():
ContainerDefinition container;
container.addPortMappings(PortMapping.builder()
.containerPort(3000)
.build());
Sometimes it is useful to be able to configure port ranges for a container, e.g. to run applications such as game servers and real-time streaming which typically require multiple ports to be opened simultaneously. This feature is supported on both Linux and Windows operating systems for both the EC2 and AWS Fargate launch types. There is a maximum limit of 100 port ranges per container, and you cannot specify overlapping port ranges.
Docker recommends that you turn off the docker-proxy in the Docker daemon config file when you have a large number of ports.
For more information, see Issue #11185 on the GitHub website.
ContainerDefinition container;
container.addPortMappings(PortMapping.builder()
.containerPort(ContainerDefinition.CONTAINER_PORT_USE_RANGE)
.containerPortRange("8080-8081")
.build());
To add data volumes to a task definition, call addVolume():
FargateTaskDefinition fargateTaskDefinition = FargateTaskDefinition.Builder.create(this, "TaskDef")
.memoryLimitMiB(512)
.cpu(256)
.build();
Map<String, Object> volume = Map.of(
// Use an Elastic FileSystem
"name", "mydatavolume",
"efsVolumeConfiguration", Map.of(
"fileSystemId", "EFS"));
void container = fargateTaskDefinition.addVolume(volume);
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:
TaskDefinition taskDefinition = TaskDefinition.Builder.create(this, "TaskDef")
.memoryMiB("512")
.cpu("256")
.networkMode(NetworkMode.AWS_VPC)
.compatibility(Compatibility.EC2_AND_FARGATE)
.build();
To grant a principal permission to run your TaskDefinition, you can use the TaskDefinition.grantRun() method:
IGrantable role;
TaskDefinition taskDef = TaskDefinition.Builder.create(this, "TaskDef")
.cpu("512")
.memoryMiB("512")
.compatibility(Compatibility.EC2_AND_FARGATE)
.build();
// Gives role required permissions to run taskDef
taskDef.grantRun(role);
To deploy containerized applications that require the allocation of standard input (stdin) or a terminal (tty), use the interactive property.
This parameter corresponds to OpenStdin in the Create a container section of the Docker Remote API
and the --interactive option to docker run.
TaskDefinition taskDefinition;
taskDefinition.addContainer("Container", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
.interactive(true)
.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.
ecs.ContainerImage.fromRegistry(imageName): use a public image.ecs.ContainerImage.fromRegistry(imageName, { credentials: mySecret }): use a private image that requires credentials.ecs.ContainerImage.fromEcrRepository(repo, tagOrDigest): use the given ECR repository as the image to start. If no tag or digest is provided, "latest" is assumed.ecs.ContainerImage.fromAsset('./image'): build and upload an image directly from aDockerfilein your source directory.ecs.ContainerImage.fromDockerImageAsset(asset): uses an existingaws-cdk-lib/aws-ecr-assets.DockerImageAssetas a container image.ecs.ContainerImage.fromTarball(file): use an existing tarball.new ecs.TagParameterContainerImage(repository): use the given ECR repository as the image but a CloudFormation parameter as the tag.
Environment variables
To pass environment variables to the container, you can use the environment, environmentFiles, and secrets props.
Secret secret;
Secret dbSecret;
StringParameter parameter;
TaskDefinition taskDefinition;
Bucket s3Bucket;
ContainerDefinition newContainer = taskDefinition.addContainer("container", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
.memoryLimitMiB(1024)
.environment(Map.of( // clear text, not for sensitive data
"STAGE", "prod"))
.environmentFiles(List.of(EnvironmentFile.fromAsset("./demo-env-file.env"), 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", Secret.fromSecretsManager(secret),
"DB_PASSWORD", Secret.fromSecretsManager(dbSecret, "password"), // Reference a specific JSON field, (requires platform version 1.4.0 or later for Fargate tasks)
"API_KEY", Secret.fromSecretsManagerVersion(secret, SecretVersionInfo.builder().versionId("12345").build(), "apiKey"), // Reference a specific version of the secret by its version id or version stage (requires platform version 1.4.0 or later for Fargate tasks)
"PARAMETER", Secret.fromSsmParameter(parameter)))
.build());
newContainer.addEnvironment("QUEUE_NAME", "MyQueue");
newContainer.addSecret("API_KEY", Secret.fromSecretsManager(secret));
newContainer.addSecret("DB_PASSWORD", Secret.fromSecretsManager(secret, "password"));
The task execution role is automatically granted read permissions on the secrets/parameters. Further details provided in the AWS documentation about specifying environment variables.
Linux parameters
To apply additional linux-specific options related to init process and memory management to the container, use the linuxParameters property:
TaskDefinition taskDefinition;
taskDefinition.addContainer("container", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
.memoryLimitMiB(1024)
.linuxParameters(LinuxParameters.Builder.create(this, "LinuxParameters")
.initProcessEnabled(true)
.sharedMemorySize(1024)
.maxSwap(Size.mebibytes(5000))
.swappiness(90)
.build())
.build());
System controls
To set system controls (kernel parameters) on the container, use the systemControls prop:
TaskDefinition taskDefinition;
taskDefinition.addContainer("container", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
.memoryLimitMiB(1024)
.systemControls(List.of(SystemControl.builder()
.namespace("net.ipv6.conf.all.default.disable_ipv6")
.value("1")
.build()))
.build());
Restart policy
To enable a restart policy for the container, set enableRestartPolicy to true and also specify
restartIgnoredExitCodes and restartAttemptPeriod if necessary.
TaskDefinition taskDefinition;
taskDefinition.addContainer("container", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
.enableRestartPolicy(true)
.restartIgnoredExitCodes(List.of(0, 127))
.restartAttemptPeriod(Duration.seconds(360))
.build());
Enable Fault Injection
You can utilize fault injection with Amazon ECS on both Amazon EC2 and Fargate to test how their application responds to certain impairment scenarios. These tests provide information you can use to optimize your application's performance and resiliency.
When fault injection is enabled, the Amazon ECS container agent allows tasks access to new fault injection endpoints.
Fault injection only works with tasks using the AWS_VPC or HOST network modes.
For more infomation, see Use fault injection with your Amazon ECS and Fargate workloads.
To enable Fault Injection for the task definiton, set enableFaultInjection to true.
Ec2TaskDefinition.Builder.create(this, "Ec2TaskDefinition")
.enableFaultInjection(true)
.build();
Docker labels
You can add labels to the container with the dockerLabels property or with the addDockerLabel method:
TaskDefinition taskDefinition;
ContainerDefinition container = taskDefinition.addContainer("cont", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
.memoryLimitMiB(1024)
.dockerLabels(Map.of(
"foo", "bar"))
.build());
container.addDockerLabel("label", "value");
Using Windows containers on Fargate
AWS Fargate supports Amazon ECS Windows containers. For more details, please see this blog post
// Create a Task Definition for the Windows container to start
FargateTaskDefinition taskDefinition = FargateTaskDefinition.Builder.create(this, "TaskDef")
.runtimePlatform(RuntimePlatform.builder()
.operatingSystemFamily(OperatingSystemFamily.WINDOWS_SERVER_2019_CORE)
.cpuArchitecture(CpuArchitecture.X86_64)
.build())
.cpu(1024)
.memoryLimitMiB(2048)
.build();
taskDefinition.addContainer("windowsservercore", ContainerDefinitionOptions.builder()
.logging(LogDriver.awsLogs(AwsLogDriverProps.builder().streamPrefix("win-iis-on-fargate").build()))
.portMappings(List.of(PortMapping.builder().containerPort(80).build()))
.image(ContainerImage.fromRegistry("mcr.microsoft.com/windows/servercore/iis:windowsservercore-ltsc2019"))
.build());
Using Windows authentication with gMSA
Amazon ECS supports Active Directory authentication for Linux containers through a special kind of service account called a group Managed Service Account (gMSA). For more details, please see the product documentation on how to implement on Windows containers, or this blog post on how to implement on Linux containers.
There are two types of CredentialSpecs, domained-join or domainless. Both types support creation from a S3 bucket, a SSM parameter, or by directly specifying a location for the file in the constructor.
A domian-joined gMSA container looks like:
// Make sure the task definition's execution role has permissions to read from the S3 bucket or SSM parameter where the CredSpec file is stored.
IParameter parameter;
TaskDefinition taskDefinition;
// Domain-joined gMSA container from a SSM parameter
taskDefinition.addContainer("gmsa-domain-joined-container", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
.cpu(128)
.memoryLimitMiB(256)
.credentialSpecs(List.of(DomainJoinedCredentialSpec.fromSsmParameter(parameter)))
.build());
A domianless gMSA container looks like:
// Make sure the task definition's execution role has permissions to read from the S3 bucket or SSM parameter where the CredSpec file is stored.
Bucket bucket;
TaskDefinition taskDefinition;
// Domainless gMSA container from a S3 bucket object.
taskDefinition.addContainer("gmsa-domainless-container", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
.cpu(128)
.memoryLimitMiB(256)
.credentialSpecs(List.of(DomainlessCredentialSpec.fromS3Bucket(bucket, "credSpec")))
.build());
Using Graviton2 with Fargate
AWS Graviton2 supports AWS Fargate. For more details, please see this blog post
// Create a Task Definition for running container on Graviton Runtime.
FargateTaskDefinition taskDefinition = FargateTaskDefinition.Builder.create(this, "TaskDef")
.runtimePlatform(RuntimePlatform.builder()
.operatingSystemFamily(OperatingSystemFamily.LINUX)
.cpuArchitecture(CpuArchitecture.ARM64)
.build())
.cpu(1024)
.memoryLimitMiB(2048)
.build();
taskDefinition.addContainer("webarm64", ContainerDefinitionOptions.builder()
.logging(LogDriver.awsLogs(AwsLogDriverProps.builder().streamPrefix("graviton2-on-fargate").build()))
.portMappings(List.of(PortMapping.builder().containerPort(80).build()))
.image(ContainerImage.fromRegistry("public.ecr.aws/nginx/nginx:latest-arm64v8"))
.build());
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.
Cluster cluster;
TaskDefinition taskDefinition;
FargateService service = FargateService.Builder.create(this, "Service")
.cluster(cluster)
.taskDefinition(taskDefinition)
.desiredCount(5)
.minHealthyPercent(100)
.build();
ECS Anywhere service definition looks like:
Cluster cluster;
TaskDefinition taskDefinition;
ExternalService service = ExternalService.Builder.create(this, "Service")
.cluster(cluster)
.taskDefinition(taskDefinition)
.desiredCount(5)
.minHealthyPercent(100)
.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.
By default, the service will use the revision of the passed task definition generated when the TaskDefinition
is deployed by CloudFormation. However, this may not be desired if the revision is externally managed,
for example through CodeDeploy.
To set a specific revision number or the special latest revision, use the taskDefinitionRevision parameter:
Cluster cluster;
TaskDefinition taskDefinition;
ExternalService.Builder.create(this, "Service")
.cluster(cluster)
.taskDefinition(taskDefinition)
.desiredCount(5)
.minHealthyPercent(100)
.taskDefinitionRevision(TaskDefinitionRevision.of(1))
.build();
ExternalService.Builder.create(this, "Service")
.cluster(cluster)
.taskDefinition(taskDefinition)
.desiredCount(5)
.minHealthyPercent(100)
.taskDefinitionRevision(TaskDefinitionRevision.LATEST)
.build();
Deployment circuit breaker and rollback
Amazon ECS deployment circuit breaker automatically rolls back unhealthy service deployments, eliminating the need for manual intervention.
Use circuitBreaker to enable the deployment circuit breaker which determines whether a service deployment
will fail if the service can't reach a steady state.
You can optionally enable rollback for automatic rollback.
See Using the deployment circuit breaker for more details.
Cluster cluster;
TaskDefinition taskDefinition;
FargateService service = FargateService.Builder.create(this, "Service")
.cluster(cluster)
.taskDefinition(taskDefinition)
.minHealthyPercent(100)
.circuitBreaker(DeploymentCircuitBreaker.builder()
.enable(true)
.rollback(true)
.build())
.build();
Note: ECS Anywhere doesn't support deployment circuit breakers and rollback.
Deployment alarms
Amazon ECS [deployment alarms] (https://aws.amazon.com/blogs/containers/automate-rollbacks-for-amazon-ecs-rolling-deployments-with-cloudwatch-alarms/) allow monitoring and automatically reacting to changes during a rolling update by using Amazon CloudWatch metric alarms.
Amazon ECS starts monitoring the configured deployment alarms as soon as one or more tasks of the updated service are in a running state. The deployment process continues until the primary deployment is healthy and has reached the desired count and the active deployment has been scaled down to 0. Then, the deployment remains in the IN_PROGRESS state for an additional "bake time." The length the bake time is calculated based on the evaluation periods and period of the alarms. After the bake time, if none of the alarms have been activated, then Amazon ECS considers this to be a successful update and deletes the active deployment and changes the status of the primary deployment to COMPLETED.
import software.amazon.awscdk.services.cloudwatch.*;
Cluster cluster;
TaskDefinition taskDefinition;
Alarm elbAlarm;
FargateService service = FargateService.Builder.create(this, "Service")
.cluster(cluster)
.taskDefinition(taskDefinition)
.minHealthyPercent(100)
.deploymentAlarms(DeploymentAlarmConfig.builder()
.alarmNames(List.of(elbAlarm.getAlarmName()))
.behavior(AlarmBehavior.ROLLBACK_ON_ALARM)
.build())
.build();
// Defining a deployment alarm after the service has been created
String cpuAlarmName = "MyCpuMetricAlarm";
Alarm.Builder.create(this, "CPUAlarm")
.alarmName(cpuAlarmName)
.metric(service.metricCpuUtilization())
.evaluationPeriods(2)
.threshold(80)
.build();
service.enableDeploymentAlarms(List.of(cpuAlarmName), DeploymentAlarmOptions.builder()
.behavior(AlarmBehavior.FAIL_ON_ALARM)
.build());
Note: Deployment alarms are only available when
deploymentControlleris set toDeploymentControllerType.ECS, which is the default.
Troubleshooting circular dependencies
I saw this info message during synth time. What do I do?
Deployment alarm ({"Ref":"MyAlarmABC1234"}) enabled on MyEcsService may cause a
circular dependency error when this stack deploys. The alarm name references the
alarm's logical id, or another resource. See the 'Deployment alarms' section in
the module README for more details.
If your app deploys successfully with this message, you can disregard it. But it indicates that you could encounter a circular dependency error when you try to deploy. If you want to alarm on metrics produced by the service, there will be a circular dependency between the service and its deployment alarms. In this case, there are two options to avoid the circular dependency.
- Define the physical name for the alarm. Use a defined physical name that is unique within the deployment environment for the alarm name when creating the alarm, and re-use the defined name. This name could be a hardcoded string, a string generated based on the environment, or could reference another resource that does not depend on the service.
- Define the physical name for the service. Then, don't use
metricCpuUtilization()or similar methods. Create the metric object separately by referencing the service metrics using this name.
Option 1, defining a physical name for the alarm:
import software.amazon.awscdk.services.cloudwatch.*;
Cluster cluster;
TaskDefinition taskDefinition;
FargateService service = FargateService.Builder.create(this, "Service")
.cluster(cluster)
.taskDefinition(taskDefinition)
.build();
String cpuAlarmName = "MyCpuMetricAlarm";
Alarm myAlarm = Alarm.Builder.create(this, "CPUAlarm")
.alarmName(cpuAlarmName)
.metric(service.metricCpuUtilization())
.evaluationPeriods(2)
.threshold(80)
.build();
// Using `myAlarm.alarmName` here will cause a circular dependency
service.enableDeploymentAlarms(List.of(cpuAlarmName), DeploymentAlarmOptions.builder()
.behavior(AlarmBehavior.FAIL_ON_ALARM)
.build());
Option 2, defining a physical name for the service:
import software.amazon.awscdk.services.cloudwatch.*;
Cluster cluster;
TaskDefinition taskDefinition;
String serviceName = "MyFargateService";
FargateService service = FargateService.Builder.create(this, "Service")
.serviceName(serviceName)
.cluster(cluster)
.taskDefinition(taskDefinition)
.minHealthyPercent(100)
.build();
Metric cpuMetric = Metric.Builder.create()
.metricName("CPUUtilization")
.namespace("AWS/ECS")
.period(Duration.minutes(5))
.statistic("Average")
.dimensionsMap(Map.of(
"ClusterName", cluster.getClusterName(),
// Using `service.serviceName` here will cause a circular dependency
"ServiceName", serviceName))
.build();
Alarm myAlarm = Alarm.Builder.create(this, "CPUAlarm")
.alarmName("cpuAlarmName")
.metric(cpuMetric)
.evaluationPeriods(2)
.threshold(80)
.build();
service.enableDeploymentAlarms(List.of(myAlarm.getAlarmName()), DeploymentAlarmOptions.builder()
.behavior(AlarmBehavior.FAIL_ON_ALARM)
.build());
This issue only applies if the metrics to alarm on are emitted by the service itself. If the metrics are emitted by a different resource, that does not depend on the service, there will be no restrictions on the alarm name.
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:
Vpc vpc;
Cluster cluster;
TaskDefinition taskDefinition;
FargateService service = FargateService.Builder.create(this, "Service").cluster(cluster).taskDefinition(taskDefinition).minHealthyPercent(100).build();
ApplicationLoadBalancer lb = ApplicationLoadBalancer.Builder.create(this, "LB").vpc(vpc).internetFacing(true).build();
ApplicationListener listener = lb.addListener("Listener", BaseApplicationListenerProps.builder().port(80).build());
ApplicationTargetGroup targetGroup1 = listener.addTargets("ECS1", AddApplicationTargetsProps.builder()
.port(80)
.targets(List.of(service))
.build());
ApplicationTargetGroup targetGroup2 = listener.addTargets("ECS2", AddApplicationTargetsProps.builder()
.port(80)
.targets(List.of(service.loadBalancerTarget(LoadBalancerTargetOptions.builder()
.containerName("MyContainer")
.containerPort(8080)
.build())))
.build());
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.
Cluster cluster;
TaskDefinition taskDefinition;
Vpc vpc;
FargateService service = FargateService.Builder.create(this, "Service").cluster(cluster).taskDefinition(taskDefinition).minHealthyPercent(100).build();
ApplicationLoadBalancer lb = ApplicationLoadBalancer.Builder.create(this, "LB").vpc(vpc).internetFacing(true).build();
ApplicationListener listener = lb.addListener("Listener", BaseApplicationListenerProps.builder().port(80).build());
service.registerLoadBalancerTargets(EcsTarget.builder()
.containerName("web")
.containerPort(80)
.newTargetGroupId("ECS")
.listener(ListenerConfig.applicationListener(listener, AddApplicationTargetsProps.builder()
.protocol(ApplicationProtocol.HTTPS)
.build()))
.build());
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:
Cluster cluster; TaskDefinition taskDefinition; Vpc vpc; Ec2Service service = Ec2Service.Builder.create(this, "Service").cluster(cluster).taskDefinition(taskDefinition).minHealthyPercent(100).build(); LoadBalancer lb = LoadBalancer.Builder.create(this, "LB").vpc(vpc).build(); lb.addListener(LoadBalancerListener.builder().externalPort(80).build()); lb.addTarget(service);
Similarly, if you want to have more control over load balancer targeting:
Cluster cluster;
TaskDefinition taskDefinition;
Vpc vpc;
Ec2Service service = Ec2Service.Builder.create(this, "Service").cluster(cluster).taskDefinition(taskDefinition).minHealthyPercent(100).build();
LoadBalancer lb = LoadBalancer.Builder.create(this, "LB").vpc(vpc).build();
lb.addListener(LoadBalancerListener.builder().externalPort(80).build());
lb.addTarget(service.loadBalancerTarget(LoadBalancerTargetOptions.builder()
.containerName("MyContainer")
.containerPort(80)
.build()));
There are two higher-level constructs available which include a load balancer for you that can be found in the aws-ecs-patterns module:
LoadBalancedFargateServiceLoadBalancedEc2Service
Import existing services
Ec2Service and FargateService provide methods to import existing EC2/Fargate services.
The ARN of the existing service has to be specified to import the service.
Since AWS has changed the ARN format for ECS,
feature flag @aws-cdk/aws-ecs:arnFormatIncludesClusterName must be enabled to use the new ARN format.
The feature flag changes behavior for the entire CDK project. Therefore it is not possible to mix the old and the new format in one CDK project.
declare const cluster: ecs.Cluster;
// Import service from EC2 service attributes
const service = ecs.Ec2Service.fromEc2ServiceAttributes(this, 'EcsService', {
serviceArn: 'arn:aws:ecs:us-west-2:123456789012:service/my-http-service',
cluster,
});
// Import service from EC2 service ARN
const service = ecs.Ec2Service.fromEc2ServiceArn(this, 'EcsService', 'arn:aws:ecs:us-west-2:123456789012:service/my-http-service');
// Import service from Fargate service attributes
const service = ecs.FargateService.fromFargateServiceAttributes(this, 'EcsService', {
serviceArn: 'arn:aws:ecs:us-west-2:123456789012:service/my-http-service',
cluster,
});
// Import service from Fargate service ARN
const service = ecs.FargateService.fromFargateServiceArn(this, 'EcsService', 'arn:aws:ecs:us-west-2:123456789012:service/my-http-service');
Availability Zone rebalancing
ECS services running in AWS can be launched in multiple VPC subnets that are each in different Availability Zones (AZs) to achieve high availability. Fargate services launched this way will automatically try to achieve an even spread of service tasks across AZs, and EC2 services can be instructed to do the same with placement strategies. This ensures that the service has equal availability in each AZ.
Vpc vpc;
Cluster cluster;
TaskDefinition taskDefinition;
FargateService service = FargateService.Builder.create(this, "Service")
.cluster(cluster)
.taskDefinition(taskDefinition)
// Fargate will try to ensure an even spread of newly launched tasks across
// all AZs corresponding to the public subnets of the VPC.
.vpcSubnets(SubnetSelection.builder().subnetType(SubnetType.PUBLIC).build())
.build();
However, those approaches only affect how newly launched tasks are placed. Service tasks can still become unevenly spread across AZs if there is an infrastructure event, like an AZ outage or a lack of available compute capacity in an AZ. During such events, newly launched tasks may be placed in AZs in such a way that tasks are not evenly spread across all AZs. After the infrastructure event is over, the service will remain imbalanced until new tasks are launched for some other reason, such as a service deployment.
Availability Zone rebalancing is a feature whereby ECS actively tries to correct service AZ imbalances whenever they exist, by moving service tasks from overbalanced AZs to underbalanced AZs. When an imbalance is detected, ECS will launch new tasks in underbalanced AZs, then stop existing tasks in overbalanced AZs, to ensure an even spread.
You can enabled Availability Zone rebalancing when creating your service:
Cluster cluster;
TaskDefinition taskDefinition;
FargateService service = FargateService.Builder.create(this, "Service")
.cluster(cluster)
.taskDefinition(taskDefinition)
.availabilityZoneRebalancing(AvailabilityZoneRebalancing.ENABLED)
.build();
Availability Zone rebalancing works in the following configurations:
- Services that use the Replica strategy.
- Services that specify Availability Zone spread as the first task placement strategy, or do not specify a placement strategy.
You can't use Availability Zone rebalancing with services that meet any of the following criteria:
- Uses the Daemon strategy.
- Uses the EXTERNAL launch type (ECSAnywhere).
- Uses 100% for the maximumPercent value.
- Uses a Classic Load Balancer.
- Uses the
attribute:ecs.availability-zoneas a task placement constraint.
Task Auto-Scaling
You can configure the task count of a service to match demand. Task auto-scaling is
configured by calling autoScaleTaskCount():
ApplicationTargetGroup target;
BaseService service;
ScalableTaskCount scaling = service.autoScaleTaskCount(EnableScalingProps.builder().maxCapacity(10).build());
scaling.scaleOnCpuUtilization("CpuScaling", CpuUtilizationScalingProps.builder()
.targetUtilizationPercent(50)
.build());
scaling.scaleOnRequestCount("RequestScaling", RequestCountScalingProps.builder()
.requestsPerTarget(10000)
.targetGroup(target)
.build());
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-lib/aws-events-targets.EcsTask instead of an Ec2Service:
Cluster cluster;
// Create a Task Definition for the container to start
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromAsset(resolve(__dirname, "..", "eventhandler-image")))
.memoryLimitMiB(256)
.logging(AwsLogDriver.Builder.create().streamPrefix("EventDemo").mode(AwsLogDriverMode.NON_BLOCKING).build())
.build());
// An Rule that describes the event trigger (in this case a scheduled run)
Rule rule = Rule.Builder.create(this, "Rule")
.schedule(Schedule.expression("rate(1 minute)"))
.build();
// Pass an environment variable to the container 'TheContainer' in the task
rule.addTarget(EcsTask.Builder.create()
.cluster(cluster)
.taskDefinition(taskDefinition)
.taskCount(1)
.containerOverrides(List.of(ContainerOverride.builder()
.containerName("TheContainer")
.environment(List.of(TaskEnvironmentVariable.builder()
.name("I_WAS_TRIGGERED")
.value("From CloudWatch Events")
.build()))
.build()))
.build());
Log Drivers
Currently Supported Log Drivers:
- awslogs
- fluentd
- gelf
- journald
- json-file
- splunk
- syslog
- awsfirelens
- Generic
awslogs Log Driver
// Create a Task Definition for the container to start
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("example-image"))
.memoryLimitMiB(256)
.logging(LogDrivers.awsLogs(AwsLogDriverProps.builder()
.streamPrefix("EventDemo")
.mode(AwsLogDriverMode.NON_BLOCKING)
.maxBufferSize(Size.mebibytes(25))
.build()))
.build());
fluentd Log Driver
// Create a Task Definition for the container to start
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("example-image"))
.memoryLimitMiB(256)
.logging(LogDrivers.fluentd())
.build());
gelf Log Driver
// Create a Task Definition for the container to start
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("example-image"))
.memoryLimitMiB(256)
.logging(LogDrivers.gelf(GelfLogDriverProps.builder().address("my-gelf-address").build()))
.build());
journald Log Driver
// Create a Task Definition for the container to start
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("example-image"))
.memoryLimitMiB(256)
.logging(LogDrivers.journald())
.build());
json-file Log Driver
// Create a Task Definition for the container to start
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("example-image"))
.memoryLimitMiB(256)
.logging(LogDrivers.jsonFile())
.build());
splunk Log Driver
Secret secret;
// Create a Task Definition for the container to start
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("example-image"))
.memoryLimitMiB(256)
.logging(LogDrivers.splunk(SplunkLogDriverProps.builder()
.secretToken(secret)
.url("my-splunk-url")
.build()))
.build());
syslog Log Driver
// Create a Task Definition for the container to start
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("example-image"))
.memoryLimitMiB(256)
.logging(LogDrivers.syslog())
.build());
firelens Log Driver
// Create a Task Definition for the container to start
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("example-image"))
.memoryLimitMiB(256)
.logging(LogDrivers.firelens(FireLensLogDriverProps.builder()
.options(Map.of(
"Name", "firehose",
"region", "us-west-2",
"delivery_stream", "my-stream"))
.build()))
.build());
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.
Secret secret;
StringParameter parameter;
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("example-image"))
.memoryLimitMiB(256)
.logging(LogDrivers.firelens(FireLensLogDriverProps.builder()
.options(Map.of())
.secretOptions(Map.of( // Retrieved from AWS Secrets Manager or AWS Systems Manager Parameter Store
"apikey", Secret.fromSecretsManager(secret),
"host", Secret.fromSsmParameter(parameter)))
.build()))
.build());
When forwarding logs to CloudWatch Logs using Fluent Bit, you can set the retention period for the newly created Log Group by specifying the log_retention_days parameter.
If a Fluent Bit container has not been added, CDK will automatically add it to the task definition, and the necessary IAM permissions will be added to the task role.
If you are adding the Fluent Bit container manually, ensure to add the logs:PutRetentionPolicy policy to the task role.
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("example-image"))
.memoryLimitMiB(256)
.logging(LogDrivers.firelens(FireLensLogDriverProps.builder()
.options(Map.of(
"Name", "cloudwatch",
"region", "us-west-2",
"log_group_name", "firelens-fluent-bit",
"log_stream_prefix", "from-fluent-bit",
"auto_create_group", "true",
"log_retention_days", "1"))
.build()))
.build());
Visit Fluent Bit CloudWatch Configuration Parameters for more details.
Generic Log Driver
A generic log driver object exists to provide a lower level abstraction of the log driver configuration.
// Create a Task Definition for the container to start
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("example-image"))
.memoryLimitMiB(256)
.logging(GenericLogDriver.Builder.create()
.logDriver("fluentd")
.options(Map.of(
"tag", "example-tag"))
.build())
.build());
CloudMap Service Discovery
To register your ECS service with a CloudMap Service Registry, you may add the
cloudMapOptions property to your service:
TaskDefinition taskDefinition;
Cluster cluster;
Ec2Service service = Ec2Service.Builder.create(this, "Service")
.cluster(cluster)
.taskDefinition(taskDefinition)
.cloudMapOptions(CloudMapOptions.builder()
// Create A records - useful for AWSVPC network mode.
.dnsRecordType(DnsRecordType.A)
.build())
.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:
TaskDefinition taskDefinition;
Cluster cluster;
// Add a container to the task definition
ContainerDefinition specificContainer = taskDefinition.addContainer("Container", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("/aws/aws-example-app"))
.memoryLimitMiB(2048)
.build());
// Add a port mapping
specificContainer.addPortMappings(PortMapping.builder()
.containerPort(7600)
.protocol(Protocol.TCP)
.build());
Ec2Service.Builder.create(this, "Service")
.cluster(cluster)
.taskDefinition(taskDefinition)
.minHealthyPercent(100)
.cloudMapOptions(CloudMapOptions.builder()
// Create SRV records - useful for bridge networking
.dnsRecordType(DnsRecordType.SRV)
// Targets port TCP port 7600 `specificContainer`
.container(specificContainer)
.containerPort(7600)
.build())
.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:
Service cloudMapService;
FargateService ecsService;
ecsService.associateCloudMapService(AssociateCloudMapServiceOptions.builder()
.service(cloudMapService)
.build());
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.
Vpc vpc;
Cluster cluster = Cluster.Builder.create(this, "FargateCPCluster")
.vpc(vpc)
.enableFargateCapacityProviders(true)
.build();
FargateTaskDefinition taskDefinition = new FargateTaskDefinition(this, "TaskDef");
taskDefinition.addContainer("web", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
.build());
FargateService.Builder.create(this, "FargateService")
.cluster(cluster)
.taskDefinition(taskDefinition)
.minHealthyPercent(100)
.capacityProviderStrategies(List.of(CapacityProviderStrategy.builder()
.capacityProvider("FARGATE_SPOT")
.weight(2)
.build(), CapacityProviderStrategy.builder()
.capacityProvider("FARGATE")
.weight(1)
.build()))
.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.
Note: Cross-stack capacity provider registration is not supported. The ECS cluster and its capacity providers must be created in the same stack to avoid circular dependency issues.
By default, Auto Scaling Group Capacity Providers will manage the scale-in and
scale-out behavior of the auto scaling group based on the load your tasks put on
the cluster, this is called Managed Scaling. If you'd
rather manage scaling behavior yourself set enableManagedScaling to false.
Additionally Managed Termination Protection is enabled by default to
prevent scale-in behavior from terminating instances that have non-daemon tasks
running on them. This is ideal for tasks that can be run to completion. If your
tasks are safe to interrupt then this protection can be disabled by setting
enableManagedTerminationProtection to false. Managed Scaling must be enabled for
Managed Termination Protection to work.
Currently there is a known CloudFormation issue that prevents CloudFormation from automatically deleting Auto Scaling Groups that have Managed Termination Protection enabled. To work around this issue you could set
enableManagedTerminationProtectiontofalseon the Auto Scaling Group Capacity Provider. If you'd rather not disable Managed Termination Protection, you can manually delete the Auto Scaling Group. For other workarounds, see this GitHub issue.
Managed instance draining facilitates graceful termination of Amazon ECS instances. This allows your service workloads to stop safely and be rescheduled to non-terminating instances. Infrastructure maintenance and updates are preformed without disruptions to workloads. To use managed instance draining, set enableManagedDraining to true.
Vpc vpc;
Cluster cluster = Cluster.Builder.create(this, "Cluster")
.vpc(vpc)
.build();
AutoScalingGroup autoScalingGroup = AutoScalingGroup.Builder.create(this, "ASG")
.vpc(vpc)
.instanceType(new InstanceType("t2.micro"))
.machineImage(EcsOptimizedImage.amazonLinux2())
.minCapacity(0)
.maxCapacity(100)
.build();
AsgCapacityProvider capacityProvider = AsgCapacityProvider.Builder.create(this, "AsgCapacityProvider")
.autoScalingGroup(autoScalingGroup)
.instanceWarmupPeriod(300)
.build();
cluster.addAsgCapacityProvider(capacityProvider);
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("web", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
.memoryReservationMiB(256)
.build());
Ec2Service.Builder.create(this, "EC2Service")
.cluster(cluster)
.taskDefinition(taskDefinition)
.minHealthyPercent(100)
.capacityProviderStrategies(List.of(CapacityProviderStrategy.builder()
.capacityProvider(capacityProvider.getCapacityProviderName())
.weight(1)
.build()))
.build();
Managed Instances Capacity Providers
Managed Instances Capacity Providers allow you to use AWS-managed EC2 instances for your ECS tasks while providing more control over instance selection than standard Fargate. AWS handles the instance lifecycle, patching, and maintenance while you can specify detailed instance requirements. You can define detailed instance requirements to control which types of instances are used for your workloads.
See ECS documentation for Managed Instances Capacity Provider for more documentation.
Vpc vpc;
Role infrastructureRole;
InstanceProfile instanceProfile;
Cluster cluster = Cluster.Builder.create(this, "Cluster").vpc(vpc).build();
// Create a Managed Instances Capacity Provider
ManagedInstancesCapacityProvider miCapacityProvider = ManagedInstancesCapacityProvider.Builder.create(this, "MICapacityProvider")
.infrastructureRole(infrastructureRole)
.ec2InstanceProfile(instanceProfile)
.subnets(vpc.getPrivateSubnets())
.securityGroups(List.of(SecurityGroup.Builder.create(this, "MISecurityGroup").vpc(vpc).build()))
.instanceRequirements(InstanceRequirementsConfig.builder()
.vCpuCountMin(1)
.memoryMin(Size.gibibytes(2))
.cpuManufacturers(List.of(CpuManufacturer.INTEL))
.acceleratorManufacturers(List.of(AcceleratorManufacturer.NVIDIA))
.build())
.propagateTags(PropagateManagedInstancesTags.CAPACITY_PROVIDER)
.build();
// Optionally configure security group rules using IConnectable interface
miCapacityProvider.connections.allowFrom(Peer.ipv4(vpc.getVpcCidrBlock()), Port.tcp(80));
// Add the capacity provider to the cluster
cluster.addManagedInstancesCapacityProvider(miCapacityProvider);
TaskDefinition taskDefinition = TaskDefinition.Builder.create(this, "TaskDef")
.memoryMiB("512")
.cpu("256")
.networkMode(NetworkMode.AWS_VPC)
.compatibility(Compatibility.MANAGED_INSTANCES)
.build();
taskDefinition.addContainer("web", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
.memoryReservationMiB(256)
.build());
FargateService.Builder.create(this, "FargateService")
.cluster(cluster)
.taskDefinition(taskDefinition)
.minHealthyPercent(100)
.capacityProviderStrategies(List.of(CapacityProviderStrategy.builder()
.capacityProvider(miCapacityProvider.getCapacityProviderName())
.weight(1)
.build()))
.build();
You can specify detailed instance requirements to control which types of instances are used:
Role infrastructureRole;
InstanceProfile instanceProfile;
Vpc vpc;
ManagedInstancesCapacityProvider miCapacityProvider = ManagedInstancesCapacityProvider.Builder.create(this, "MICapacityProvider")
.infrastructureRole(infrastructureRole)
.ec2InstanceProfile(instanceProfile)
.subnets(vpc.getPrivateSubnets())
.instanceRequirements(InstanceRequirementsConfig.builder()
// Required: CPU and memory constraints
.vCpuCountMin(2)
.vCpuCountMax(8)
.memoryMin(Size.gibibytes(4))
.memoryMax(Size.gibibytes(32))
// CPU preferences
.cpuManufacturers(List.of(CpuManufacturer.INTEL, CpuManufacturer.AMD))
.instanceGenerations(List.of(InstanceGeneration.CURRENT))
// Instance type filtering
.allowedInstanceTypes(List.of("m5.*", "c5.*"))
// Performance characteristics
.burstablePerformance(BurstablePerformance.EXCLUDED)
.bareMetal(BareMetal.EXCLUDED)
// Accelerator requirements (for ML/AI workloads)
.acceleratorTypes(List.of(AcceleratorType.GPU))
.acceleratorManufacturers(List.of(AcceleratorManufacturer.NVIDIA))
.acceleratorNames(List.of(AcceleratorName.T4, AcceleratorName.V100))
.acceleratorCountMin(1)
// Storage requirements
.localStorage(LocalStorage.REQUIRED)
.localStorageTypes(List.of(LocalStorageType.SSD))
.totalLocalStorageGBMin(100)
// Network requirements
.networkInterfaceCountMin(2)
.networkBandwidthGbpsMin(10)
// Cost optimization
.onDemandMaxPricePercentageOverLowestPrice(10)
.build())
.build();
Note: Service Replacement When Migrating from LaunchType to CapacityProviderStrategy
Understanding the Limitation
The ECS CreateService API does not allow specifying both launchType and capacityProviderStrategies simultaneously. When you specify capacityProviderStrategies, the CDK uses those capacity providers instead of a launch type. This is a limitation of the ECS API and CloudFormation, not a CDK bug.
Impact on Updates
Because launchType is immutable during updates, switching from launchType to capacityProviderStrategies requires CloudFormation to replace the service. This means your existing service will be deleted and recreated with the new configuration. This behavior is expected and reflects the underlying API constraints.
Workaround
While we work on a long-term solution, you can use the following escape hatch to preserve your service during the migration:
Cluster cluster;
TaskDefinition taskDefinition;
ManagedInstancesCapacityProvider miCapacityProvider;
FargateService service = FargateService.Builder.create(this, "Service")
.cluster(cluster)
.taskDefinition(taskDefinition)
.capacityProviderStrategies(List.of(CapacityProviderStrategy.builder()
.capacityProvider(miCapacityProvider.getCapacityProviderName())
.weight(1)
.build()))
.build();
// Escape hatch: Force launchType at the CloudFormation level to prevent service replacement
CfnService cfnService = (CfnService)service.getNode().getDefaultChild();
cfnService.getLaunchType() = "FARGATE";
Cluster Default Provider Strategy
A capacity provider strategy determines whether ECS tasks are launched on EC2 instances or Fargate/Fargate Spot. It can be specified at the cluster, service, or task level, and consists of one or more capacity providers. You can specify an optional base and weight value for finer control of how tasks are launched. The base specifies a minimum number of tasks on one capacity provider, and the weights of each capacity provider determine how tasks are distributed after base is satisfied.
You can associate a default capacity provider strategy with an Amazon ECS cluster. After you do this, a default capacity provider strategy is used when creating a service or running a standalone task in the cluster and whenever a custom capacity provider strategy or a launch type isn't specified. We recommend that you define a default capacity provider strategy for each cluster.
For more information visit https://docs.aws.amazon.com/AmazonECS/latest/developerguide/cluster-capacity-providers.html
When the service does not have a capacity provider strategy, the cluster's default capacity provider strategy will be used. Default Capacity Provider Strategy can be added by using the method addDefaultCapacityProviderStrategy. A capacity provider strategy cannot contain a mix of EC2 Autoscaling Group capacity providers and Fargate providers.
AsgCapacityProvider capacityProvider;
Cluster cluster = Cluster.Builder.create(this, "EcsCluster")
.enableFargateCapacityProviders(true)
.build();
cluster.addAsgCapacityProvider(capacityProvider);
cluster.addDefaultCapacityProviderStrategy(List.of(CapacityProviderStrategy.builder().capacityProvider("FARGATE").base(10).weight(50).build(), CapacityProviderStrategy.builder().capacityProvider("FARGATE_SPOT").weight(50).build()));
AsgCapacityProvider capacityProvider;
Cluster cluster = Cluster.Builder.create(this, "EcsCluster")
.enableFargateCapacityProviders(true)
.build();
cluster.addAsgCapacityProvider(capacityProvider);
cluster.addDefaultCapacityProviderStrategy(List.of(CapacityProviderStrategy.builder().capacityProvider(capacityProvider.getCapacityProviderName()).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.
Map<String, String>[] inferenceAccelerators = List.of(Map.of(
"deviceName", "device1",
"deviceType", "eia2.medium"));
Ec2TaskDefinition taskDefinition = Ec2TaskDefinition.Builder.create(this, "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.
TaskDefinition taskDefinition;
String[] inferenceAcceleratorResources = List.of("device1");
taskDefinition.addContainer("cont", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("test"))
.memoryLimitMiB(1024)
.inferenceAcceleratorResources(inferenceAcceleratorResources)
.build());
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, FargateService or ExternalService.
Cluster cluster;
TaskDefinition taskDefinition;
Ec2Service service = Ec2Service.Builder.create(this, "Service")
.cluster(cluster)
.taskDefinition(taskDefinition)
.minHealthyPercent(100)
.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.
Vpc vpc;
Key kmsKey = new Key(this, "KmsKey");
// Pass the KMS key in the `encryptionKey` field to associate the key to the log group
LogGroup logGroup = LogGroup.Builder.create(this, "LogGroup")
.encryptionKey(kmsKey)
.build();
// Pass the KMS key in the `encryptionKey` field to associate the key to the S3 bucket
Bucket execBucket = Bucket.Builder.create(this, "EcsExecBucket")
.encryptionKey(kmsKey)
.build();
Cluster cluster = Cluster.Builder.create(this, "Cluster")
.vpc(vpc)
.executeCommandConfiguration(ExecuteCommandConfiguration.builder()
.kmsKey(kmsKey)
.logConfiguration(ExecuteCommandLogConfiguration.builder()
.cloudWatchLogGroup(logGroup)
.cloudWatchEncryptionEnabled(true)
.s3Bucket(execBucket)
.s3EncryptionEnabled(true)
.s3KeyPrefix("exec-command-output")
.build())
.logging(ExecuteCommandLogging.OVERRIDE)
.build())
.build();
Amazon ECS Service Connect
Service Connect is a managed AWS mesh network offering. It simplifies DNS queries and inter-service communication for ECS Services by allowing customers to set up simple DNS aliases for their services, which are accessible to all services that have enabled Service Connect.
To enable Service Connect, you must have created a CloudMap namespace. The CDK can infer your cluster's default CloudMap namespace, or you can specify a custom namespace. You must also have created a named port mapping on at least one container in your Task Definition.
Cluster cluster;
TaskDefinition taskDefinition;
ContainerDefinitionOptions containerOptions;
ContainerDefinition container = taskDefinition.addContainer("MyContainer", containerOptions);
container.addPortMappings(PortMapping.builder()
.name("api")
.containerPort(8080)
.build());
cluster.addDefaultCloudMapNamespace(CloudMapNamespaceOptions.builder()
.name("local")
.build());
FargateService service = FargateService.Builder.create(this, "Service")
.cluster(cluster)
.taskDefinition(taskDefinition)
.minHealthyPercent(100)
.serviceConnectConfiguration(ServiceConnectProps.builder()
.services(List.of(ServiceConnectService.builder()
.portMappingName("api")
.dnsName("http-api")
.port(80)
.build()))
.build())
.build();
Service Connect-enabled services may now reach this service at http-api:80. Traffic to this endpoint will
be routed to the container's port 8080.
To opt a service into using service connect without advertising a port, simply call the 'enableServiceConnect' method on an initialized service.
Cluster cluster;
TaskDefinition taskDefinition;
FargateService service = FargateService.Builder.create(this, "Service")
.cluster(cluster)
.taskDefinition(taskDefinition)
.minHealthyPercent(100)
.build();
service.enableServiceConnect();
Service Connect also allows custom logging, Service Discovery name, and configuration of the port where service connect traffic is received.
Cluster cluster;
TaskDefinition taskDefinition;
FargateService customService = FargateService.Builder.create(this, "CustomizedService")
.cluster(cluster)
.taskDefinition(taskDefinition)
.minHealthyPercent(100)
.serviceConnectConfiguration(ServiceConnectProps.builder()
.logDriver(LogDrivers.awsLogs(AwsLogDriverProps.builder()
.streamPrefix("sc-traffic")
.build()))
.services(List.of(ServiceConnectService.builder()
.portMappingName("api")
.dnsName("customized-api")
.port(80)
.ingressPortOverride(20040)
.discoveryName("custom")
.build()))
.build())
.build();
To set a timeout for service connect, use idleTimeout and perRequestTimeout.
Note: If idleTimeout is set to a time that is less than perRequestTimeout, the connection will close when
the idleTimeout is reached and not the perRequestTimeout.
Cluster cluster;
TaskDefinition taskDefinition;
FargateService service = FargateService.Builder.create(this, "Service")
.cluster(cluster)
.taskDefinition(taskDefinition)
.minHealthyPercent(100)
.serviceConnectConfiguration(ServiceConnectProps.builder()
.services(List.of(ServiceConnectService.builder()
.portMappingName("api")
.idleTimeout(Duration.minutes(5))
.perRequestTimeout(Duration.minutes(5))
.build()))
.build())
.build();
Visit Amazon ECS support for configurable timeout for services running with Service Connect for more details.
ServiceManagedVolume
Amazon ECS now supports the attachment of Amazon Elastic Block Store (EBS) volumes to ECS tasks,
allowing you to utilize persistent, high-performance block storage with your ECS services.
This feature supports various use cases, such as using EBS volumes as extended ephemeral storage or
loading data from EBS snapshots.
You can also specify encrypted: true so that ECS will manage the KMS key. If you want to use your own KMS key, you may do so by providing both encrypted: true and kmsKeyId.
You can only attach a single volume for each task in the ECS Service.
To add an empty EBS Volume to an ECS Service, call service.addVolume().
Cluster cluster;
FargateTaskDefinition taskDefinition = new FargateTaskDefinition(this, "TaskDef");
ContainerDefinition container = taskDefinition.addContainer("web", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
.portMappings(List.of(PortMapping.builder()
.containerPort(80)
.protocol(Protocol.TCP)
.build()))
.build());
ServiceManagedVolume volume = ServiceManagedVolume.Builder.create(this, "EBSVolume")
.name("ebs1")
.managedEBSVolume(ServiceManagedEBSVolumeConfiguration.builder()
.size(Size.gibibytes(15))
.volumeType(EbsDeviceVolumeType.GP3)
.fileSystemType(FileSystemType.XFS)
.tagSpecifications(List.of(EBSTagSpecification.builder()
.tags(Map.of(
"purpose", "production"))
.propagateTags(EbsPropagatedTagSource.SERVICE)
.build()))
.build())
.build();
volume.mountIn(container, ContainerMountPoint.builder()
.containerPath("/var/lib")
.readOnly(false)
.build());
taskDefinition.addVolume(volume);
FargateService service = FargateService.Builder.create(this, "FargateService")
.cluster(cluster)
.taskDefinition(taskDefinition)
.minHealthyPercent(100)
.build();
service.addVolume(volume);
To create an EBS volume from an existing snapshot by specifying the snapShotId while adding a volume to the service.
ContainerDefinition container;
Cluster cluster;
TaskDefinition taskDefinition;
ServiceManagedVolume volumeFromSnapshot = ServiceManagedVolume.Builder.create(this, "EBSVolume")
.name("nginx-vol")
.managedEBSVolume(ServiceManagedEBSVolumeConfiguration.builder()
.snapShotId("snap-066877671789bd71b")
.volumeType(EbsDeviceVolumeType.GP3)
.fileSystemType(FileSystemType.XFS)
// Specifies the Amazon EBS Provisioned Rate for Volume Initialization.
// Valid range is between 100 and 300 MiB/s.
.volumeInitializationRate(Size.mebibytes(200))
.build())
.build();
volumeFromSnapshot.mountIn(container, ContainerMountPoint.builder()
.containerPath("/var/lib")
.readOnly(false)
.build());
taskDefinition.addVolume(volumeFromSnapshot);
FargateService service = FargateService.Builder.create(this, "FargateService")
.cluster(cluster)
.taskDefinition(taskDefinition)
.minHealthyPercent(100)
.build();
service.addVolume(volumeFromSnapshot);
Enable pseudo-terminal (TTY) allocation
You can allocate a pseudo-terminal (TTY) for a container passing pseudoTerminal option while adding the container
to the task definition.
This maps to Tty option in the "Create a container section"
of the Docker Remote API and the --tty option to docker run.
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("example-image"))
.pseudoTerminal(true)
.build());
Disable service container image version consistency
You can disable the container image "version consistency" feature of ECS service deployments on a per-container basis.
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("example-image"))
.versionConsistency(VersionConsistency.DISABLED)
.build());
Specify a container ulimit
You can specify a container ulimits by specifying them in the ulimits option while adding the container
to the task definition.
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("example-image"))
.ulimits(List.of(Ulimit.builder()
.hardLimit(128)
.name(UlimitName.RSS)
.softLimit(128)
.build()))
.build());
Service Connect TLS
Service Connect TLS is a feature that allows you to secure the communication between services using TLS.
You can specify the tls option in the services array of the serviceConnectConfiguration property.
The tls property is an object with the following properties:
role: The IAM role that's associated with the Service Connect TLS.awsPcaAuthorityArn: The ARN of the certificate root authority that secures your service.kmsKey: The KMS key used for encryption and decryption.
Cluster cluster;
TaskDefinition taskDefinition;
IKey kmsKey;
IRole role;
FargateService service = FargateService.Builder.create(this, "FargateService")
.cluster(cluster)
.taskDefinition(taskDefinition)
.serviceConnectConfiguration(ServiceConnectProps.builder()
.services(List.of(ServiceConnectService.builder()
.tls(ServiceConnectTlsConfiguration.builder()
.role(role)
.kmsKey(kmsKey)
.awsPcaAuthorityArn("arn:aws:acm-pca:us-east-1:123456789012:certificate-authority/123456789012")
.build())
.portMappingName("api")
.build()))
.namespace("sample namespace")
.build())
.build();
ECS Native Blue/Green Deployment
Amazon ECS supports native blue/green deployments that allow you to deploy new versions of your services with zero downtime. This deployment strategy creates a new set of tasks (green) alongside the existing tasks (blue), then shifts traffic from the old version to the new version.
Amazon ECS blue/green deployments
import software.amazon.awscdk.services.lambda.*;
Cluster cluster;
TaskDefinition taskDefinition;
Function lambdaHook;
ApplicationTargetGroup blueTargetGroup;
ApplicationTargetGroup greenTargetGroup;
ApplicationListenerRule prodListenerRule;
FargateService service = FargateService.Builder.create(this, "Service")
.cluster(cluster)
.taskDefinition(taskDefinition)
.deploymentStrategy(DeploymentStrategy.BLUE_GREEN)
.build();
service.addLifecycleHook(DeploymentLifecycleLambdaTarget.Builder.create(lambdaHook, "PreScaleHook")
.lifecycleStages(List.of(DeploymentLifecycleStage.PRE_SCALE_UP))
.build());
IEcsLoadBalancerTarget target = service.loadBalancerTarget(LoadBalancerTargetOptions.builder()
.containerName("nginx")
.containerPort(80)
.protocol(Protocol.TCP)
.alternateTarget(AlternateTarget.Builder.create("AlternateTarget")
.alternateTargetGroup(greenTargetGroup)
.productionListener(ListenerRuleConfiguration.applicationListenerRule(prodListenerRule))
.build())
.build());
target.attachToApplicationTargetGroup(blueTargetGroup);
Daemon Scheduling Strategy
You can specify whether service use Daemon scheduling strategy by specifying daemon option in Service constructs. See differences between Daemon and Replica scheduling strategy
Cluster cluster;
TaskDefinition taskDefinition;
Ec2Service.Builder.create(this, "Ec2Service")
.cluster(cluster)
.taskDefinition(taskDefinition)
.daemon(true)
.build();
ExternalService.Builder.create(this, "ExternalService")
.cluster(cluster)
.taskDefinition(taskDefinition)
.daemon(true)
.build();
-
ClassDescriptionThe properties for adding an AutoScalingGroup.A builder for
AddAutoScalingGroupCapacityOptionsAn implementation forAddAutoScalingGroupCapacityOptionsThe properties for adding instance capacity to an AutoScalingGroup.A builder forAddCapacityOptionsAn implementation forAddCapacityOptionsDeployment behavior when an ECS Service Deployment Alarm is triggered.Configuration for alternate target groups used in blue/green deployments with load balancers.A fluent builder forAlternateTarget.Configuration returned by AlternateTargetConfiguration.bind().A builder forAlternateTargetConfigAn implementation forAlternateTargetConfigOptions for AlternateTarget configuration.A builder forAlternateTargetOptionsAn implementation forAlternateTargetOptionsProperties for AlternateTarget configuration.A builder forAlternateTargetPropsAn implementation forAlternateTargetPropsThe ECS-optimized AMI variant to use.The class for App Mesh proxy configurations.A fluent builder forAppMeshProxyConfiguration.The configuration to use when setting an App Mesh proxy configuration.A builder forAppMeshProxyConfigurationConfigPropsAn implementation forAppMeshProxyConfigurationConfigPropsInterface for setting the properties of proxy configuration.A builder forAppMeshProxyConfigurationPropsAn implementation forAppMeshProxyConfigurationPropsService connect app protocol.An Auto Scaling Group Capacity Provider.A fluent builder forAsgCapacityProvider.The options for creating an Auto Scaling Group Capacity Provider.A builder forAsgCapacityProviderPropsAn implementation forAsgCapacityProviderPropsEnvironment file from a local directory.A fluent builder forAssetEnvironmentFile.An image that will be built from a local directory with a Dockerfile.A fluent builder forAssetImage.The properties for building an AssetImage.A builder forAssetImagePropsAn implementation forAssetImagePropsThe options for using a cloudmap service.A builder forAssociateCloudMapServiceOptionsAn implementation forAssociateCloudMapServiceOptionsThe authorization configuration details for the Amazon EFS file system.A builder forAuthorizationConfigAn implementation forAuthorizationConfigIndicates whether to use Availability Zone rebalancing for an ECS service.A log driver that sends log information to CloudWatch Logs.A fluent builder forAwsLogDriver.awslogs provides two modes for delivering messages from the container to the log driver.Specifies the awslogs log driver configuration options.A builder forAwsLogDriverPropsAn implementation forAwsLogDriverPropsExample:A builder forBaseLogDriverPropsAn implementation forBaseLogDriverPropsThe base details of where a volume will be mounted within a container.A builder forBaseMountPointAn implementation forBaseMountPointThe base class for Ec2Service and FargateService services.The properties for the base Ec2Service or FargateService service.A builder forBaseServiceOptionsAn implementation forBaseServiceOptionsComplete base service properties that are required to be supplied by the implementation of the BaseService class.A builder forBaseServicePropsAn implementation forBaseServicePropsInstance resource used for bin packing.Amazon ECS variant.Construct an Bottlerocket image from the latest AMI published in SSM.A fluent builder forBottleRocketImage.Properties for BottleRocketImage.A builder forBottleRocketImagePropsAn implementation forBottleRocketImagePropsThe built-in container instance attributes.A Linux capability.A Capacity Provider strategy to use for the service.A builder forCapacityProviderStrategyAn implementation forCapacityProviderStrategyCreates a capacity provider.The minimum and maximum number of accelerators (such as GPUs) for instance type selection.A builder forCfnCapacityProvider.AcceleratorCountRequestPropertyAn implementation forCfnCapacityProvider.AcceleratorCountRequestPropertyThe minimum and maximum total accelerator memory in mebibytes (MiB) for instance type selection.An implementation forCfnCapacityProvider.AcceleratorTotalMemoryMiBRequestPropertyThe details of the Auto Scaling group for the capacity provider.A builder forCfnCapacityProvider.AutoScalingGroupProviderPropertyAn implementation forCfnCapacityProvider.AutoScalingGroupProviderPropertyThe minimum and maximum baseline Amazon EBS bandwidth in megabits per second (Mbps) for instance type selection.An implementation forCfnCapacityProvider.BaselineEbsBandwidthMbpsRequestPropertyA fluent builder forCfnCapacityProvider.Defines how Amazon ECS Managed Instances optimizes the infrastructure in your capacity provider.A builder forCfnCapacityProvider.InfrastructureOptimizationPropertyAn implementation forCfnCapacityProvider.InfrastructureOptimizationPropertyThe launch template configuration for Amazon ECS Managed Instances.A builder forCfnCapacityProvider.InstanceLaunchTemplatePropertyAn implementation forCfnCapacityProvider.InstanceLaunchTemplatePropertyThe instance requirements for attribute-based instance type selection.A builder forCfnCapacityProvider.InstanceRequirementsRequestPropertyAn implementation forCfnCapacityProvider.InstanceRequirementsRequestPropertyThe network configuration for Amazon ECS Managed Instances.An implementation forCfnCapacityProvider.ManagedInstancesNetworkConfigurationPropertyThe configuration for a Amazon ECS Managed Instances provider.A builder forCfnCapacityProvider.ManagedInstancesProviderPropertyAn implementation forCfnCapacityProvider.ManagedInstancesProviderPropertyThe storage configuration for Amazon ECS Managed Instances.An implementation forCfnCapacityProvider.ManagedInstancesStorageConfigurationPropertyThe managed scaling settings for the Auto Scaling group capacity provider.A builder forCfnCapacityProvider.ManagedScalingPropertyAn implementation forCfnCapacityProvider.ManagedScalingPropertyThe minimum and maximum amount of memory per vCPU in gibibytes (GiB).A builder forCfnCapacityProvider.MemoryGiBPerVCpuRequestPropertyAn implementation forCfnCapacityProvider.MemoryGiBPerVCpuRequestPropertyThe minimum and maximum amount of memory in mebibytes (MiB) for instance type selection.A builder forCfnCapacityProvider.MemoryMiBRequestPropertyAn implementation forCfnCapacityProvider.MemoryMiBRequestPropertyThe minimum and maximum network bandwidth in gigabits per second (Gbps) for instance type selection.A builder forCfnCapacityProvider.NetworkBandwidthGbpsRequestPropertyAn implementation forCfnCapacityProvider.NetworkBandwidthGbpsRequestPropertyThe minimum and maximum number of network interfaces for instance type selection.A builder forCfnCapacityProvider.NetworkInterfaceCountRequestPropertyAn implementation forCfnCapacityProvider.NetworkInterfaceCountRequestPropertyThe minimum and maximum total local storage in gigabytes (GB) for instance types with local storage.A builder forCfnCapacityProvider.TotalLocalStorageGBRequestPropertyAn implementation forCfnCapacityProvider.TotalLocalStorageGBRequestPropertyThe minimum and maximum number of vCPUs for instance type selection.A builder forCfnCapacityProvider.VCpuCountRangeRequestPropertyAn implementation forCfnCapacityProvider.VCpuCountRangeRequestPropertyProperties for defining aCfnCapacityProvider.A builder forCfnCapacityProviderPropsAn implementation forCfnCapacityProviderPropsTheAWS::ECS::Clusterresource creates an Amazon Elastic Container Service (Amazon ECS) cluster.A fluent builder forCfnCluster.TheCapacityProviderStrategyItemproperty specifies the details of the default capacity provider strategy for the cluster.A builder forCfnCluster.CapacityProviderStrategyItemPropertyAn implementation forCfnCluster.CapacityProviderStrategyItemPropertyThe execute command and managed storage configuration for the cluster.A builder forCfnCluster.ClusterConfigurationPropertyAn implementation forCfnCluster.ClusterConfigurationPropertyThe settings to use when creating a cluster.A builder forCfnCluster.ClusterSettingsPropertyAn implementation forCfnCluster.ClusterSettingsPropertyThe details of the execute command configuration.A builder forCfnCluster.ExecuteCommandConfigurationPropertyAn implementation forCfnCluster.ExecuteCommandConfigurationPropertyThe log configuration for the results of the execute command actions.A builder forCfnCluster.ExecuteCommandLogConfigurationPropertyAn implementation forCfnCluster.ExecuteCommandLogConfigurationPropertyThe managed storage configuration for the cluster.A builder forCfnCluster.ManagedStorageConfigurationPropertyAn implementation forCfnCluster.ManagedStorageConfigurationPropertyUse this parameter to set a default Service Connect namespace.A builder forCfnCluster.ServiceConnectDefaultsPropertyAn implementation forCfnCluster.ServiceConnectDefaultsPropertyTheAWS::ECS::ClusterCapacityProviderAssociationsresource associates one or more capacity providers and a default capacity provider strategy with a cluster.A fluent builder forCfnClusterCapacityProviderAssociations.TheCapacityProviderStrategyproperty specifies the details of the default capacity provider strategy for the cluster.An implementation forCfnClusterCapacityProviderAssociations.CapacityProviderStrategyPropertyProperties for defining aCfnClusterCapacityProviderAssociations.A builder forCfnClusterCapacityProviderAssociationsPropsAn implementation forCfnClusterCapacityProviderAssociationsPropsProperties for defining aCfnCluster.A builder forCfnClusterPropsAn implementation forCfnClusterPropsModifies which task set in a service is the primary task set.A fluent builder forCfnPrimaryTaskSet.Properties for defining aCfnPrimaryTaskSet.A builder forCfnPrimaryTaskSetPropsAn implementation forCfnPrimaryTaskSetPropsTheAWS::ECS::Serviceresource creates an Amazon Elastic Container Service (Amazon ECS) service that runs and maintains the requested number of tasks and associated load balancers.The advanced settings for a load balancer used in blue/green deployments.A builder forCfnService.AdvancedConfigurationPropertyAn implementation forCfnService.AdvancedConfigurationPropertyAn object representing the networking details for a task or service.A builder forCfnService.AwsVpcConfigurationPropertyAn implementation forCfnService.AwsVpcConfigurationPropertyA fluent builder forCfnService.Configuration for a canary deployment strategy that shifts a fixed percentage of traffic to the new service revision, waits for a specified bake time, then shifts the remaining traffic.A builder forCfnService.CanaryConfigurationPropertyAn implementation forCfnService.CanaryConfigurationPropertyThe details of a capacity provider strategy.A builder forCfnService.CapacityProviderStrategyItemPropertyAn implementation forCfnService.CapacityProviderStrategyItemPropertyOne of the methods which provide a way for you to quickly identify when a deployment has failed, and then to optionally roll back the failure to the last working deployment.A builder forCfnService.DeploymentAlarmsPropertyAn implementation forCfnService.DeploymentAlarmsPropertyA builder forCfnService.DeploymentCircuitBreakerPropertyAn implementation forCfnService.DeploymentCircuitBreakerPropertyOptional deployment parameters that control how many tasks run during a deployment and the ordering of stopping and starting tasks.A builder forCfnService.DeploymentConfigurationPropertyAn implementation forCfnService.DeploymentConfigurationPropertyThe deployment controller to use for the service.A builder forCfnService.DeploymentControllerPropertyAn implementation forCfnService.DeploymentControllerPropertyA deployment lifecycle hook runs custom logic at specific stages of the deployment process.A builder forCfnService.DeploymentLifecycleHookPropertyAn implementation forCfnService.DeploymentLifecycleHookPropertyThe tag specifications of an Amazon EBS volume.A builder forCfnService.EBSTagSpecificationPropertyAn implementation forCfnService.EBSTagSpecificationPropertyDetermines whether to force a new deployment of the service.A builder forCfnService.ForceNewDeploymentPropertyAn implementation forCfnService.ForceNewDeploymentPropertyConfiguration for a linear deployment strategy that shifts production traffic in equal percentage increments with configurable wait times between each step until 100 percent of traffic is shifted to the new service revision.A builder forCfnService.LinearConfigurationPropertyAn implementation forCfnService.LinearConfigurationPropertyTheLoadBalancerproperty specifies details on a load balancer that is used with a service.A builder forCfnService.LoadBalancerPropertyAn implementation forCfnService.LoadBalancerPropertyThe log configuration for the container.A builder forCfnService.LogConfigurationPropertyAn implementation forCfnService.LogConfigurationPropertyThe network configuration for a task or service.A builder forCfnService.NetworkConfigurationPropertyAn implementation forCfnService.NetworkConfigurationPropertyAn object representing a constraint on task placement.A builder forCfnService.PlacementConstraintPropertyAn implementation forCfnService.PlacementConstraintPropertyThe task placement strategy for a task or service.A builder forCfnService.PlacementStrategyPropertyAn implementation forCfnService.PlacementStrategyPropertyAn object representing the secret to expose to your container.A builder forCfnService.SecretPropertyAn implementation forCfnService.SecretPropertyConfiguration for Service Connect access logging.A builder forCfnService.ServiceConnectAccessLogConfigurationPropertyAn implementation forCfnService.ServiceConnectAccessLogConfigurationPropertyEach alias ("endpoint") is a fully-qualified name and port number that other tasks ("clients") can use to connect to this service.A builder forCfnService.ServiceConnectClientAliasPropertyAn implementation forCfnService.ServiceConnectClientAliasPropertyThe Service Connect configuration of your Amazon ECS service.A builder forCfnService.ServiceConnectConfigurationPropertyAn implementation forCfnService.ServiceConnectConfigurationPropertyThe Service Connect service object configuration.A builder forCfnService.ServiceConnectServicePropertyAn implementation forCfnService.ServiceConnectServicePropertyExample:A builder forCfnService.ServiceConnectTestTrafficRulesHeaderPropertyAn implementation forCfnService.ServiceConnectTestTrafficRulesHeaderPropertyExample:An implementation forCfnService.ServiceConnectTestTrafficRulesHeaderValuePropertyThe test traffic routing configuration for Amazon ECS blue/green deployments.A builder forCfnService.ServiceConnectTestTrafficRulesPropertyAn implementation forCfnService.ServiceConnectTestTrafficRulesPropertyThe certificate root authority that secures your service.A builder forCfnService.ServiceConnectTlsCertificateAuthorityPropertyAn implementation forCfnService.ServiceConnectTlsCertificateAuthorityPropertyThe key that encrypts and decrypts your resources for Service Connect TLS.A builder forCfnService.ServiceConnectTlsConfigurationPropertyAn implementation forCfnService.ServiceConnectTlsConfigurationPropertyThe configuration for the Amazon EBS volume that Amazon ECS creates and manages on your behalf.A builder forCfnService.ServiceManagedEBSVolumeConfigurationPropertyAn implementation forCfnService.ServiceManagedEBSVolumeConfigurationPropertyThe details for the service registry.A builder forCfnService.ServiceRegistryPropertyAn implementation forCfnService.ServiceRegistryPropertyThe configuration for a volume specified in the task definition as a volume that is configured at launch time.A builder forCfnService.ServiceVolumeConfigurationPropertyAn implementation forCfnService.ServiceVolumeConfigurationPropertyAn object that represents the timeout configurations for Service Connect.A builder forCfnService.TimeoutConfigurationPropertyAn implementation forCfnService.TimeoutConfigurationPropertyThe VPC Lattice configuration for your service that holds the information for the target group(s) Amazon ECS tasks will be registered to.A builder forCfnService.VpcLatticeConfigurationPropertyAn implementation forCfnService.VpcLatticeConfigurationPropertyProperties for defining aCfnService.A builder forCfnServicePropsAn implementation forCfnServicePropsRegisters a new task definition from the suppliedfamilyandcontainerDefinitions.The authorization configuration details for the Amazon EFS file system.A builder forCfnTaskDefinition.AuthorizationConfigPropertyAn implementation forCfnTaskDefinition.AuthorizationConfigPropertyA fluent builder forCfnTaskDefinition.TheContainerDefinitionproperty specifies a container definition.A builder forCfnTaskDefinition.ContainerDefinitionPropertyAn implementation forCfnTaskDefinition.ContainerDefinitionPropertyTheContainerDependencyproperty specifies the dependencies defined for container startup and shutdown.A builder forCfnTaskDefinition.ContainerDependencyPropertyAn implementation forCfnTaskDefinition.ContainerDependencyPropertyTheDeviceproperty specifies an object representing a container instance host device.A builder forCfnTaskDefinition.DevicePropertyAn implementation forCfnTaskDefinition.DevicePropertyTheDockerVolumeConfigurationproperty specifies a Docker volume configuration and is used when you use Docker volumes.A builder forCfnTaskDefinition.DockerVolumeConfigurationPropertyAn implementation forCfnTaskDefinition.DockerVolumeConfigurationPropertyThis parameter is specified when you're using an Amazon Elastic File System file system for task storage.A builder forCfnTaskDefinition.EFSVolumeConfigurationPropertyAn implementation forCfnTaskDefinition.EFSVolumeConfigurationPropertyA list of files containing the environment variables to pass to a container.A builder forCfnTaskDefinition.EnvironmentFilePropertyAn implementation forCfnTaskDefinition.EnvironmentFilePropertyThe amount of ephemeral storage to allocate for the task.A builder forCfnTaskDefinition.EphemeralStoragePropertyAn implementation forCfnTaskDefinition.EphemeralStoragePropertyThe FireLens configuration for the container.A builder forCfnTaskDefinition.FirelensConfigurationPropertyAn implementation forCfnTaskDefinition.FirelensConfigurationPropertyThe authorization configuration details for Amazon FSx for Windows File Server file system.A builder forCfnTaskDefinition.FSxAuthorizationConfigPropertyAn implementation forCfnTaskDefinition.FSxAuthorizationConfigPropertyThis parameter is specified when you're using Amazon FSx for Windows File Server file system for task storage.An implementation forCfnTaskDefinition.FSxWindowsFileServerVolumeConfigurationPropertyTheHealthCheckproperty specifies an object representing a container health check.A builder forCfnTaskDefinition.HealthCheckPropertyAn implementation forCfnTaskDefinition.HealthCheckPropertyTheHostEntryproperty specifies a hostname and an IP address that are added to the/etc/hostsfile of a container through theextraHostsparameter of itsContainerDefinitionresource.A builder forCfnTaskDefinition.HostEntryPropertyAn implementation forCfnTaskDefinition.HostEntryPropertyTheHostVolumePropertiesproperty specifies details on a container instance bind mount host volume.A builder forCfnTaskDefinition.HostVolumePropertiesPropertyAn implementation forCfnTaskDefinition.HostVolumePropertiesPropertyExample:A builder forCfnTaskDefinition.InferenceAcceleratorPropertyAn implementation forCfnTaskDefinition.InferenceAcceleratorPropertyThe Linux capabilities to add or remove from the default Docker configuration for a container defined in the task definition.A builder forCfnTaskDefinition.KernelCapabilitiesPropertyAn implementation forCfnTaskDefinition.KernelCapabilitiesPropertyA key-value pair object.A builder forCfnTaskDefinition.KeyValuePairPropertyAn implementation forCfnTaskDefinition.KeyValuePairPropertyThe Linux-specific options that are applied to the container, such as Linux KernelCapabilities .A builder forCfnTaskDefinition.LinuxParametersPropertyAn implementation forCfnTaskDefinition.LinuxParametersPropertyTheLogConfigurationproperty specifies log configuration options to send to a custom log driver for the container.A builder forCfnTaskDefinition.LogConfigurationPropertyAn implementation forCfnTaskDefinition.LogConfigurationPropertyThe details for a volume mount point that's used in a container definition.A builder forCfnTaskDefinition.MountPointPropertyAn implementation forCfnTaskDefinition.MountPointPropertyThePortMappingproperty specifies a port mapping.A builder forCfnTaskDefinition.PortMappingPropertyAn implementation forCfnTaskDefinition.PortMappingPropertyThe configuration details for the App Mesh proxy.A builder forCfnTaskDefinition.ProxyConfigurationPropertyAn implementation forCfnTaskDefinition.ProxyConfigurationPropertyThe repository credentials for private registry authentication.A builder forCfnTaskDefinition.RepositoryCredentialsPropertyAn implementation forCfnTaskDefinition.RepositoryCredentialsPropertyThe type and amount of a resource to assign to a container.A builder forCfnTaskDefinition.ResourceRequirementPropertyAn implementation forCfnTaskDefinition.ResourceRequirementPropertyYou can enable a restart policy for each container defined in your task definition, to overcome transient failures faster and maintain task availability.A builder forCfnTaskDefinition.RestartPolicyPropertyAn implementation forCfnTaskDefinition.RestartPolicyPropertyInformation about the platform for the Amazon ECS service or task.A builder forCfnTaskDefinition.RuntimePlatformPropertyAn implementation forCfnTaskDefinition.RuntimePlatformPropertyAn object representing the secret to expose to your container.A builder forCfnTaskDefinition.SecretPropertyAn implementation forCfnTaskDefinition.SecretPropertyA list of namespaced kernel parameters to set in the container.A builder forCfnTaskDefinition.SystemControlPropertyAn implementation forCfnTaskDefinition.SystemControlPropertyThe constraint on task placement in the task definition.An implementation forCfnTaskDefinition.TaskDefinitionPlacementConstraintPropertyThe container path, mount options, and size of the tmpfs mount.A builder forCfnTaskDefinition.TmpfsPropertyAn implementation forCfnTaskDefinition.TmpfsPropertyTheulimitsettings to pass to the container.A builder forCfnTaskDefinition.UlimitPropertyAn implementation forCfnTaskDefinition.UlimitPropertyDetails on a data volume from another container in the same task definition.A builder forCfnTaskDefinition.VolumeFromPropertyAn implementation forCfnTaskDefinition.VolumeFromPropertyThe data volume configuration for tasks launched using this task definition.A builder forCfnTaskDefinition.VolumePropertyAn implementation forCfnTaskDefinition.VolumePropertyProperties for defining aCfnTaskDefinition.A builder forCfnTaskDefinitionPropsAn implementation forCfnTaskDefinitionPropsCreate a task set in the specified cluster and service.An object representing the networking details for a task or service.A builder forCfnTaskSet.AwsVpcConfigurationPropertyAn implementation forCfnTaskSet.AwsVpcConfigurationPropertyA fluent builder forCfnTaskSet.The details of a capacity provider strategy.A builder forCfnTaskSet.CapacityProviderStrategyItemPropertyAn implementation forCfnTaskSet.CapacityProviderStrategyItemPropertyThe load balancer configuration to use with a service or task set.A builder forCfnTaskSet.LoadBalancerPropertyAn implementation forCfnTaskSet.LoadBalancerPropertyThe network configuration for a task or service.A builder forCfnTaskSet.NetworkConfigurationPropertyAn implementation forCfnTaskSet.NetworkConfigurationPropertyA floating-point percentage of the desired number of tasks to place and keep running in the task set.A builder forCfnTaskSet.ScalePropertyAn implementation forCfnTaskSet.ScalePropertyThe details for the service registry.A builder forCfnTaskSet.ServiceRegistryPropertyAn implementation forCfnTaskSet.ServiceRegistryPropertyProperties for defining aCfnTaskSet.A builder forCfnTaskSetPropsAn implementation forCfnTaskSetPropsThe options for creating an AWS Cloud Map namespace.A builder forCloudMapNamespaceOptionsAn implementation forCloudMapNamespaceOptionsThe options to enabling AWS Cloud Map for an Amazon ECS service.A builder forCloudMapOptionsAn implementation forCloudMapOptionsA regional grouping of one or more container instances on which you can run tasks and services.A fluent builder forCluster.The properties to import from the ECS cluster.A builder forClusterAttributesAn implementation forClusterAttributesCollection of grant methods for a IClusterRef.The properties used to define an ECS cluster.A builder forClusterPropsAn implementation forClusterPropsThe common task definition attributes used across all types of task definitions.A builder forCommonTaskDefinitionAttributesAn implementation forCommonTaskDefinitionAttributesThe common properties for all task definitions.A builder forCommonTaskDefinitionPropsAn implementation forCommonTaskDefinitionPropsThe task launch type compatibility requirement.A container definition is used in a task definition to describe the containers that are launched as part of a task.A fluent builder forContainerDefinition.Example:A builder forContainerDefinitionOptionsAn implementation forContainerDefinitionOptionsThe properties in a container definition.A builder forContainerDefinitionPropsAn implementation forContainerDefinitionPropsThe details of a dependency on another container in the task definition.A builder forContainerDependencyAn implementation forContainerDependencyConstructs for types of container images.The configuration for creating a container image.A builder forContainerImageConfigAn implementation forContainerImageConfigThe CloudWatch Container Insights setting.Defines the mount point details for attaching a volume to a container.A builder forContainerMountPointAn implementation forContainerMountPointThe CpuArchitecture for Fargate Runtime Platform.The properties for enabling scaling based on CPU utilization.A builder forCpuUtilizationScalingPropsAn implementation forCpuUtilizationScalingPropsBase construct for a credential specification (CredSpec).Configuration for a credential specification (CredSpec) used for a ECS container.A builder forCredentialSpecConfigAn implementation forCredentialSpecConfigConfiguration for deployment alarms.A builder forDeploymentAlarmConfigAn implementation forDeploymentAlarmConfigOptions for deployment alarms.A builder forDeploymentAlarmOptionsAn implementation forDeploymentAlarmOptionsThe deployment circuit breaker to use for the service.A builder forDeploymentCircuitBreakerAn implementation forDeploymentCircuitBreakerThe deployment controller to use for the service.A builder forDeploymentControllerAn implementation forDeploymentControllerThe deployment controller type to use for the service.Configuration for a deployment lifecycle hook target.A builder forDeploymentLifecycleHookTargetConfigAn implementation forDeploymentLifecycleHookTargetConfigUse an AWS Lambda function as a deployment lifecycle hook target.A fluent builder forDeploymentLifecycleLambdaTarget.Configuration for a lambda deployment lifecycle hook.A builder forDeploymentLifecycleLambdaTargetPropsAn implementation forDeploymentLifecycleLambdaTargetPropsDeployment lifecycle stages where hooks can be executed.The deployment stratergy to use for ECS controller.A container instance host device.A builder forDeviceAn implementation forDevicePermissions for device access.The configuration for a Docker volume.A builder forDockerVolumeConfigurationAn implementation forDockerVolumeConfigurationCredential specification (CredSpec) file.Credential specification for domainless gMSA.Propagate tags for EBS Volume Configuration from either service or task definition.Tag Specification for EBS volume.A builder forEBSTagSpecificationAn implementation forEBSTagSpecificationThis creates a service using the EC2 launch type on an ECS cluster.A fluent builder forEc2Service.The properties to import from the service using the EC2 launch type.A builder forEc2ServiceAttributesAn implementation forEc2ServiceAttributesThe properties for defining a service using the EC2 launch type.A builder forEc2ServicePropsAn implementation forEc2ServicePropsThe details of a task definition run on an EC2 cluster.A fluent builder forEc2TaskDefinition.Attributes used to import an existing EC2 task definition.A builder forEc2TaskDefinitionAttributesAn implementation forEc2TaskDefinitionAttributesThe properties for a task definition run on an EC2 cluster.A builder forEc2TaskDefinitionPropsAn implementation forEc2TaskDefinitionPropsAn image from an Amazon ECR repository.Construct a Linux or Windows machine image from the latest ECS Optimized AMI published in SSM.Additional configuration properties for EcsOptimizedImage factory functions.A builder forEcsOptimizedImageOptionsAn implementation forEcsOptimizedImageOptionsExample:A builder forEcsTargetAn implementation forEcsTargetThe configuration for an Elastic FileSystem volume.A builder forEfsVolumeConfigurationAn implementation forEfsVolumeConfigurationConstructs for types of environment files.Configuration for the environment file.A builder forEnvironmentFileConfigAn implementation forEnvironmentFileConfigType of environment file to be included in the container definition.The details of the execute command configuration.A builder forExecuteCommandConfigurationAn implementation forExecuteCommandConfigurationThe log configuration for the results of the execute command actions.A builder forExecuteCommandLogConfigurationAn implementation forExecuteCommandLogConfigurationThe log settings to use to for logging the execute command session.This creates a service using the External launch type on an ECS cluster.A fluent builder forExternalService.The properties to import from the service using the External launch type.A builder forExternalServiceAttributesAn implementation forExternalServiceAttributesThe properties for defining a service using the External launch type.A builder forExternalServicePropsAn implementation forExternalServicePropsThe details of a task definition run on an External cluster.A fluent builder forExternalTaskDefinition.Attributes used to import an existing External task definition.A builder forExternalTaskDefinitionAttributesAn implementation forExternalTaskDefinitionAttributesThe properties for a task definition run on an External cluster.A builder forExternalTaskDefinitionPropsAn implementation forExternalTaskDefinitionPropsThe platform version on which to run your service.This creates a service using the Fargate launch type on an ECS cluster.A fluent builder forFargateService.The properties to import from the service using the Fargate launch type.A builder forFargateServiceAttributesAn implementation forFargateServiceAttributesThe properties for defining a service using the Fargate launch type.A builder forFargateServicePropsAn implementation forFargateServicePropsThe details of a task definition run on a Fargate cluster.A fluent builder forFargateTaskDefinition.Attributes used to import an existing Fargate task definition.A builder forFargateTaskDefinitionAttributesAn implementation forFargateTaskDefinitionAttributesThe properties for a task definition.A builder forFargateTaskDefinitionPropsAn implementation forFargateTaskDefinitionPropsFileSystemType for Service Managed EBS Volume Configuration.Firelens Configuration https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_firelens.html#firelens-taskdef.A builder forFirelensConfigAn implementation forFirelensConfigFirelens configuration file type, s3 or file path.FireLens enables you to use task definition parameters to route logs to an AWS service or AWS Partner Network (APN) destination for log storage and analytics.A fluent builder forFireLensLogDriver.Specifies the firelens log driver configuration options.A builder forFireLensLogDriverPropsAn implementation forFireLensLogDriverPropsFirelens log router.A fluent builder forFirelensLogRouter.The options for creating a firelens log router.A builder forFirelensLogRouterDefinitionOptionsAn implementation forFirelensLogRouterDefinitionOptionsThe properties in a firelens log router.A builder forFirelensLogRouterPropsAn implementation forFirelensLogRouterPropsFirelens log router type, fluentbit or fluentd.The options for firelens log router https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_firelens.html#firelens-taskdef-customconfig.A builder forFirelensOptionsAn implementation forFirelensOptionsA log driver that sends log information to journald Logs.A fluent builder forFluentdLogDriver.Specifies the fluentd log driver configuration options.A builder forFluentdLogDriverPropsAn implementation forFluentdLogDriverPropsThe type of compression the GELF driver uses to compress each log message.A log driver that sends log information to journald Logs.A fluent builder forGelfLogDriver.Specifies the journald log driver configuration options.A builder forGelfLogDriverPropsAn implementation forGelfLogDriverPropsA log driver that sends logs to the specified driver.A fluent builder forGenericLogDriver.The configuration to use when creating a log driver.A builder forGenericLogDriverPropsAn implementation forGenericLogDriverPropsThe health check command and associated configuration parameters for the container.A builder forHealthCheckAn implementation forHealthCheckThe details on a container instance bind mount host volume.A builder forHostAn implementation forHostInterface for configuring alternate target groups for blue/green deployments.Internal default implementation forIAlternateTarget.A proxy class which represents a concrete javascript instance of this type.The interface for BaseService.Internal default implementation forIBaseService.A proxy class which represents a concrete javascript instance of this type.A regional grouping of one or more container instances on which you can run tasks and services.Internal default implementation forICluster.A proxy class which represents a concrete javascript instance of this type.Interface for deployment lifecycle hook targets.Internal default implementation forIDeploymentLifecycleHookTarget.A proxy class which represents a concrete javascript instance of this type.The interface for a service using the EC2 launch type on an ECS cluster.Internal default implementation forIEc2Service.A proxy class which represents a concrete javascript instance of this type.The interface of a task definition run on an EC2 cluster.Internal default implementation forIEc2TaskDefinition.A proxy class which represents a concrete javascript instance of this type.Interface for ECS load balancer target.Internal default implementation forIEcsLoadBalancerTarget.A proxy class which represents a concrete javascript instance of this type.The interface for a service using the External launch type on an ECS cluster.Internal default implementation forIExternalService.A proxy class which represents a concrete javascript instance of this type.The interface of a task definition run on an External cluster.Internal default implementation forIExternalTaskDefinition.A proxy class which represents a concrete javascript instance of this type.The interface for a service using the Fargate launch type on an ECS cluster.Internal default implementation forIFargateService.A proxy class which represents a concrete javascript instance of this type.The interface of a task definition run on a Fargate cluster.Internal default implementation forIFargateTaskDefinition.A proxy class which represents a concrete javascript instance of this type.Elastic Inference Accelerator.A builder forInferenceAcceleratorAn implementation forInferenceAcceleratorThe monitoring configuration for EC2 instances.The IPC resource namespace to use for the containers in the task.The interface for a service.Internal default implementation forIService.A proxy class which represents a concrete javascript instance of this type.The interface for all task definitions.Internal default implementation forITaskDefinition.A proxy class which represents a concrete javascript instance of this type.An extension for Task Definitions.Internal default implementation forITaskDefinitionExtension.A proxy class which represents a concrete javascript instance of this type.A log driver that sends log information to journald Logs.A fluent builder forJournaldLogDriver.Specifies the journald log driver configuration options.A builder forJournaldLogDriverPropsAn implementation forJournaldLogDriverPropsA log driver that sends log information to json-file Logs.A fluent builder forJsonFileLogDriver.Specifies the json-file log driver configuration options.A builder forJsonFileLogDriverPropsAn implementation forJsonFileLogDriverPropsThe launch type of an ECS service.Linux-specific options that are applied to the container.A fluent builder forLinuxParameters.The properties for defining Linux-specific options that are applied to the container.A builder forLinuxParametersPropsAn implementation forLinuxParametersPropsBase class for configuring listener when registering targets.Represents a listener configuration for advanced load balancer settings.Properties for defining an ECS target.A builder forLoadBalancerTargetOptionsAn implementation forLoadBalancerTargetOptionsThe base class for log drivers.The configuration to use when creating a log driver.A builder forLogDriverConfigAn implementation forLogDriverConfigThe base class for log drivers.The machine image type.A Managed Instances Capacity Provider.A fluent builder forManagedInstancesCapacityProvider.The options for creating a Managed Instances Capacity Provider.A builder forManagedInstancesCapacityProviderPropsAn implementation forManagedInstancesCapacityProviderPropsKms Keys for encryption ECS managed storage.A builder forManagedStorageConfigurationAn implementation forManagedStorageConfigurationThe properties for enabling scaling based on memory utilization.A builder forMemoryUtilizationScalingPropsAn implementation forMemoryUtilizationScalingPropsThe details of data volume mount points for a container.A builder forMountPointAn implementation forMountPointThe networking mode to use for the containers in the task.The operating system for Fargate Runtime Platform.The process namespace to use for the containers in the task.The placement constraints to use for tasks in the service.The placement strategies to use for tasks in the service.PortMap ValueObjectClass having by ContainerDefinition.A fluent builder forPortMap.Port mappings allow containers to access ports on the host container instance to send or receive traffic.A builder forPortMappingAn implementation forPortMappingPropagate tags from either service or task definition.Propagate tags for Managed Instances.Network protocol.The base class for proxy configurations.The base class for proxy configurations.An image hosted in a public or private repository.A fluent builder forRepositoryImage.The properties for an image hosted in a public or private repository.A builder forRepositoryImagePropsAn implementation forRepositoryImagePropsThe properties for enabling scaling based on Application Load Balancer (ALB) request counts.A builder forRequestCountScalingPropsAn implementation forRequestCountScalingPropsThe interface for Runtime Platform.A builder forRuntimePlatformAn implementation forRuntimePlatformEnvironment file from S3.The scalable attribute representing task count.A fluent builder forScalableTaskCount.The properties of a scalable attribute representing task count.A builder forScalableTaskCountPropsAn implementation forScalableTaskCountPropsThe scope for the Docker volume that determines its lifecycle.The temporary disk space mounted to the container.A builder forScratchSpaceAn implementation forScratchSpaceA secret environment variable.Specify the secret's version id or version stage.A builder forSecretVersionInfoAn implementation forSecretVersionInfoServiceConnect ValueObjectClass having by ContainerDefinition.A fluent builder forServiceConnect.Interface for Service Connect configuration.A builder forServiceConnectPropsAn implementation forServiceConnectPropsInterface for service connect Service props.A builder forServiceConnectServiceAn implementation forServiceConnectServiceTLS configuration for Service Connect service.A builder forServiceConnectTlsConfigurationAn implementation forServiceConnectTlsConfigurationRepresents the configuration for an ECS Service managed EBS volume.A builder forServiceManagedEBSVolumeConfigurationAn implementation forServiceManagedEBSVolumeConfigurationRepresents a service-managed volume and always configured at launch.A fluent builder forServiceManagedVolume.Represents the Volume configuration for an ECS service.A builder forServiceManagedVolumePropsAn implementation forServiceManagedVolumePropsA log driver that sends log information to splunk Logs.A fluent builder forSplunkLogDriver.Specifies the splunk log driver configuration options.A builder forSplunkLogDriverPropsAn implementation forSplunkLogDriverPropsLog Message Format.A log driver that sends log information to syslog Logs.A fluent builder forSyslogLogDriver.Specifies the syslog log driver configuration options.A builder forSyslogLogDriverPropsAn implementation forSyslogLogDriverPropsKernel parameters to set in the container.A builder forSystemControlAn implementation forSystemControlA special type ofContainerImagethat uses an ECR repository for the image, but a CloudFormation Parameter for the tag of the image in that repository.The base class for all task definitions.A fluent builder forTaskDefinition.A reference to an existing task definition.A builder forTaskDefinitionAttributesAn implementation forTaskDefinitionAttributesThe properties for task definitions.A builder forTaskDefinitionPropsAn implementation forTaskDefinitionPropsRepresents revision of a task definition, either a specific numbered revision or thelatestrevision.The details of a tmpfs mount for a container.A builder forTmpfsAn implementation forTmpfsThe supported options for a tmpfs mount for a container.The properties for enabling target tracking scaling based on a custom CloudWatch metric.A builder forTrackCustomMetricPropsAn implementation forTrackCustomMetricPropsThe ulimit settings to pass to the container.A builder forUlimitAn implementation forUlimitType of resource to set a limit on.State of the container version consistency feature.A data volume used in a task definition.A builder forVolumeAn implementation forVolumeThe details on a data volume from another container in the same task definition.A builder forVolumeFromAn implementation forVolumeFromECS-optimized Windows version list.