AWSCDK::ECS

1 namespaces · 235 types

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 = nil # AWSCDK::EC2::VPC


# Create an ECS cluster
cluster = AWSCDK::ECS::Cluster.new(self, "Cluster", {vpc: vpc})

# Add capacity to it
cluster.add_capacity("DefaultAutoScalingGroupCapacity", {
    instance_type: AWSCDK::EC2::InstanceType.new("t2.xlarge"),
})

task_definition = AWSCDK::ECS::EC2TaskDefinition.new(self, "TaskDef")

task_definition.add_container("DefaultContainer", {
    image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
    memory_limit_mi_b: 512,
})

# Instantiate an Amazon ECS Service
ecs_service = AWSCDK::ECS::EC2Service.new(self, "Service", {
    cluster: cluster,
    task_definition: task_definition,
    min_healthy_percent: 100,
    circuit_breaker: {
        enable: true,
    },
})

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:

Here are the main differences:

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

Clusters

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

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

vpc = nil # AWSCDK::EC2::VPC


cluster = AWSCDK::ECS::Cluster.new(self, "Cluster", {
    vpc: vpc,
})

By default, storage is encrypted with AWS-managed key. You can specify customer-managed key using:

key = nil # AWSCDK::KMS::Key


cluster = AWSCDK::ECS::Cluster.new(self, "Cluster", {
    managed_storage_configuration: {
        fargate_ephemeral_storage_kms_key: key,
        kms_key: key,
    },
})

The following code imports an existing cluster using the ARN which can be used to import an Amazon ECS service either EC2 or Fargate.

cluster_arn = "arn:aws:ecs:us-east-1:012345678910:cluster/clusterName"

cluster = AWSCDK::ECS::Cluster.from_cluster_arn(self, "Cluster", cluster_arn)

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 = nil # AWSCDK::EC2::VPC


cluster = AWSCDK::ECS::Cluster.new(self, "Cluster", {
    vpc: vpc,
})

# Either add default capacity
cluster.add_capacity("DefaultAutoScalingGroupCapacity", {
    instance_type: AWSCDK::EC2::InstanceType.new("t2.xlarge"),
})

# Or add customized capacity. Be sure to start the Amazon ECS-optimized AMI.
auto_scaling_group = AWSCDK::Autoscaling::AutoScalingGroup.new(self, "ASG", {
    vpc: vpc,
    instance_type: AWSCDK::EC2::InstanceType.new("t2.xlarge"),
    machine_image: AWSCDK::ECS::ECSOptimizedImage.amazon_linux,
    # Or use Amazon ECS-Optimized Amazon Linux 2 AMI
    # machineImage: EcsOptimizedImage.amazonLinux2(),
    desired_capacity: 3,
})

capacity_provider = AWSCDK::ECS::AsgCapacityProvider.new(self, "AsgCapacityProvider", {
    auto_scaling_group: auto_scaling_group,
})
cluster.add_asg_capacity_provider(capacity_provider)

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 = nil # AWSCDK::EC2::VPC

auto_scaling_group = AWSCDK::Autoscaling::AutoScalingGroup.new(self, "ASG", {
    machine_image: AWSCDK::ECS::ECSOptimizedImage.amazon_linux({cached_in_context: true}),
    vpc: vpc,
    instance_type: AWSCDK::EC2::InstanceType.new("t2.micro"),
})

To customize the cache key, use the additional_cache_key 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 = nil # AWSCDK::EC2::VPC

auto_scaling_group = AWSCDK::Autoscaling::AutoScalingGroup.new(self, "ASG", {
    machine_image: AWSCDK::ECS::ECSOptimizedImage.amazon_linux({cached_in_context: true, additional_cache_key: @node.path}),
    vpc: vpc,
    instance_type: AWSCDK::EC2::InstanceType.new("t2.micro"),
})

To use LaunchTemplate with AsgCapacityProvider, make sure to specify the user_data in the LaunchTemplate:

vpc = nil # AWSCDK::EC2::VPC

launch_template = AWSCDK::EC2::LaunchTemplate.new(self, "ASG-LaunchTemplate", {
    instance_type: AWSCDK::EC2::InstanceType.new("t3.medium"),
    machine_image: AWSCDK::ECS::ECSOptimizedImage.amazon_linux2,
    user_data: AWSCDK::EC2::UserData.for_linux,
})

auto_scaling_group = AWSCDK::Autoscaling::AutoScalingGroup.new(self, "ASG", {
    vpc: vpc,
    mixed_instances_policy: {
        instances_distribution: {
            on_demand_percentage_above_base_capacity: 50,
        },
        launch_template: launch_template,
    },
})

cluster = AWSCDK::ECS::Cluster.new(self, "Cluster", {vpc: vpc})

capacity_provider = AWSCDK::ECS::AsgCapacityProvider.new(self, "AsgCapacityProvider", {
    auto_scaling_group: auto_scaling_group,
    machine_image_type: AWSCDK::ECS::MachineImageType::AMAZON_LINUX_2,
})

cluster.add_asg_capacity_provider(capacity_provider)

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 = nil # AWSCDK::ECS::Cluster
task_definition = nil # AWSCDK::ECS::TaskDefinition

task_ar_ns = cluster.arn_for_tasks("*") # arn:aws:ecs:<region>:<regionId>:task/<clusterName>/*

# Grant the task permission to access other AWS resources
task_definition.add_to_task_role_policy(
AWSCDK::IAM::PolicyStatement.new({
    actions: ["ecs:UpdateTaskProtection"],
    resources: [task_ar_ns],
}))

To manage task protection settings in an ECS cluster, you can use the grant_task_protection method. This method grants the ecs:UpdateTaskProtection permission to a specified IAM entity.

# Assume 'cluster' is an instance of ecs.Cluster
cluster = nil # AWSCDK::ECS::Cluster
task_role = nil # AWSCDK::IAM::Role


# Grant ECS Task Protection permissions to the role
# Now 'taskRole' has the 'ecs:UpdateTaskProtection' permission on all tasks in the cluster
cluster.grant_task_protection(task_role)

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 = nil # AWSCDK::ECS::Cluster


cluster.add_capacity("bottlerocket-asg", {
    min_capacity: 2,
    instance_type: AWSCDK::EC2::InstanceType.new("c5.large"),
    machine_image: AWSCDK::ECS::BottleRocketImage.new,
})

You can also specify an NVIDIA-compatible AMI such as in this example:

cluster = nil # AWSCDK::ECS::Cluster


cluster.add_capacity("bottlerocket-asg", {
    instance_type: AWSCDK::EC2::InstanceType.new("p3.2xlarge"),
    machine_image: AWSCDK::ECS::BottleRocketImage.new({
        variant: AWSCDK::ECS::BottlerocketECSVariant::AWS_ECS_2_NVIDIA,
    }),
})

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 = nil # AWSCDK::ECS::Cluster


cluster.add_capacity("graviton-cluster", {
    min_capacity: 2,
    instance_type: AWSCDK::EC2::InstanceType.new("c6g.large"),
    machine_image: AWSCDK::ECS::ECSOptimizedImage.amazon_linux2(AWSCDK::ECS::AmiHardwareType::ARM),
})

Bottlerocket is also supported:

cluster = nil # AWSCDK::ECS::Cluster


cluster.add_capacity("graviton-cluster", {
    min_capacity: 2,
    instance_type: AWSCDK::EC2::InstanceType.new("c6g.large"),
    machine_image_type: AWSCDK::ECS::MachineImageType::BOTTLEROCKET,
})

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 = nil # AWSCDK::ECS::Cluster


cluster.add_capacity("neuron-cluster", {
    min_capacity: 2,
    instance_type: AWSCDK::EC2::InstanceType.new("inf1.xlarge"),
    machine_image: AWSCDK::ECS::ECSOptimizedImage.amazon_linux2(AWSCDK::ECS::AmiHardwareType::NEURON),
})

Spot Instances

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

cluster = nil # AWSCDK::ECS::Cluster


# Add an AutoScalingGroup with spot instances to the existing cluster
cluster.add_capacity("AsgSpot", {
    max_capacity: 2,
    min_capacity: 2,
    desired_capacity: 2,
    instance_type: AWSCDK::EC2::InstanceType.new("c5.xlarge"),
    spot_price: "0.0735",
    # Enable the Automated Spot Draining support for Amazon ECS
    spot_instance_draining: true,
})

SNS Topic Encryption

When the ecs.AddCapacityOptions that you provide has a non-zero task_drain_time (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 topic_encryption_key property of ecs.AddCapacityOptions.

# Given
cluster = nil # AWSCDK::ECS::Cluster
key = nil # AWSCDK::KMS::Key

# Then, use that key to encrypt the lifecycle-event SNS Topic.
cluster.add_capacity("ASGEncryptedSNS", {
    instance_type: AWSCDK::EC2::InstanceType.new("t2.xlarge"),
    desired_capacity: 3,
    topic_encryption_key: key,
})

Container Insights

On a cluster, CloudWatch Container Insights can be enabled by setting the container_insights_v2 property. Container Insights can be disabled, enabled, or enhanced.

cluster = AWSCDK::ECS::Cluster.new(self, "Cluster", {
    container_insights_v2: AWSCDK::ECS::ContainerInsights::ENHANCED,
})

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 (memory_limit_mib and cpu):

fargate_task_definition = AWSCDK::ECS::FargateTaskDefinition.new(self, "TaskDef", {
    memory_limit_mi_b: 512,
    cpu: 256,
})

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

fargate_task_definition = AWSCDK::ECS::FargateTaskDefinition.new(self, "TaskDef", {
    memory_limit_mi_b: 512,
    cpu: 256,
    ephemeral_storage_gi_b: 100,
})

To specify the process namespace to use for the containers in the task, use the pid_mode property:

fargate_task_definition = AWSCDK::ECS::FargateTaskDefinition.new(self, "TaskDef", {
    runtime_platform: {
        operating_system_family: AWSCDK::ECS::OperatingSystemFamily.LINUX,
        cpu_architecture: AWSCDK::ECS::CpuArchitecture.ARM64,
    },
    memory_limit_mi_b: 512,
    cpu: 256,
    pid_mode: AWSCDK::ECS::PidMode::TASK,
})

Note: pid_mode 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. pid_mode isn't supported for Windows containers on Fargate. If pid_mode is specified for a Fargate task, then runtimePlatform.operatingSystemFamily must also be specified.

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

fargate_task_definition = AWSCDK::ECS::FargateTaskDefinition.new(self, "TaskDef", {
    memory_limit_mi_b: 512,
    cpu: 256,
})
container = fargate_task_definition.add_container("WebContainer", {
    # Use an image from DockerHub
    image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
})

For an Ec2TaskDefinition:

ec2_task_definition = AWSCDK::ECS::EC2TaskDefinition.new(self, "TaskDef", {
    network_mode: AWSCDK::ECS::NetworkMode::BRIDGE,
})

container = ec2_task_definition.add_container("WebContainer", {
    # Use an image from DockerHub
    image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
    memory_limit_mi_b: 1024,
})

For an ExternalTaskDefinition:

external_task_definition = AWSCDK::ECS::ExternalTaskDefinition.new(self, "TaskDef")

container = external_task_definition.add_container("WebContainer", {
    # Use an image from DockerHub
    image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
    memory_limit_mi_b: 1024,
})

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

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

task_definition = nil # AWSCDK::ECS::TaskDefinition


task_definition.add_container("WebContainer", {
    image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
    memory_limit_mi_b: 1024,
    port_mappings: [{container_port: 3000}],
})

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

container = nil # AWSCDK::ECS::ContainerDefinition


container.add_port_mappings({
    container_port: 3000,
})

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.

container = nil # AWSCDK::ECS::ContainerDefinition


container.add_port_mappings({
    container_port: AWSCDK::ECS::ContainerDefinition.CONTAINER_PORT_USE_RANGE,
    container_port_range: "8080-8081",
})

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

fargate_task_definition = AWSCDK::ECS::FargateTaskDefinition.new(self, "TaskDef", {
    memory_limit_mi_b: 512,
    cpu: 256,
})
volume = {
    # Use an Elastic FileSystem
    name: "mydatavolume",
    efs_volume_configuration: {
        file_system_id: "EFS",
    },
}

container = fargate_task_definition.add_volume(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:

task_definition = AWSCDK::ECS::TaskDefinition.new(self, "TaskDef", {
    memory_mi_b: "512",
    cpu: "256",
    network_mode: AWSCDK::ECS::NetworkMode::AWS_VPC,
    compatibility: AWSCDK::ECS::Compatibility::EC2_AND_FARGATE,
})

To grant a principal permission to run your TaskDefinition, you can use the TaskDefinition.grantRun() method:

role = nil # AWSCDK::IAM::IGrantable

task_def = AWSCDK::ECS::TaskDefinition.new(self, "TaskDef", {
    cpu: "512",
    memory_mi_b: "512",
    compatibility: AWSCDK::ECS::Compatibility::EC2_AND_FARGATE,
})

# Gives role required permissions to run taskDef
task_def.grant_run(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.

task_definition = nil # AWSCDK::ECS::TaskDefinition


task_definition.add_container("Container", {
    image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
    interactive: true,
})

Images

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

Environment variables

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

secret = nil # AWSCDK::SecretsManager::Secret
db_secret = nil # AWSCDK::SecretsManager::Secret
parameter = nil # AWSCDK::SSM::StringParameter
task_definition = nil # AWSCDK::ECS::TaskDefinition
s3_bucket = nil # AWSCDK::S3::Bucket


new_container = task_definition.add_container("container", {
    image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
    memory_limit_mi_b: 1024,
    environment: {
         # clear text, not for sensitive data
        STAGE: "prod",
    },
    environment_files: [
        AWSCDK::ECS::EnvironmentFile.from_asset("./demo-env-file.env"),
        AWSCDK::ECS::EnvironmentFile.from_bucket(s3_bucket, "assets/demo-env-file.env"),
    ],
    secrets: {
         # Retrieved from AWS Secrets Manager or AWS Systems Manager Parameter Store at container start-up.
        SECRET: AWSCDK::ECS::Secret.from_secrets_manager(secret),
        DB_PASSWORD: AWSCDK::ECS::Secret.from_secrets_manager(db_secret, "password"),
         # Reference a specific JSON field, (requires platform version 1.4.0 or later for Fargate tasks)
        API_KEY: AWSCDK::ECS::Secret.from_secrets_manager_version(secret, {version_id: "12345"}, "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: AWSCDK::ECS::Secret.from_ssm_parameter(parameter),
    },
})
new_container.add_environment("QUEUE_NAME", "MyQueue")
new_container.add_secret("API_KEY", AWSCDK::ECS::Secret.from_secrets_manager(secret))
new_container.add_secret("DB_PASSWORD", AWSCDK::ECS::Secret.from_secrets_manager(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 linux_parameters property:

task_definition = nil # AWSCDK::ECS::TaskDefinition


task_definition.add_container("container", {
    image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
    memory_limit_mi_b: 1024,
    linux_parameters: AWSCDK::ECS::LinuxParameters.new(self, "LinuxParameters", {
        init_process_enabled: true,
        shared_memory_size: 1024,
        max_swap: AWSCDK::Size.mebibytes(5000),
        swappiness: 90,
    }),
})

System controls

To set system controls (kernel parameters) on the container, use the system_controls prop:

task_definition = nil # AWSCDK::ECS::TaskDefinition


task_definition.add_container("container", {
    image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
    memory_limit_mi_b: 1024,
    system_controls: [
        {
            namespace: "net.ipv6.conf.all.default.disable_ipv6",
            value: "1",
        },
    ],
})

Restart policy

To enable a restart policy for the container, set enable_restart_policy to true and also specify restart_ignored_exit_codes and restart_attempt_period if necessary.

task_definition = nil # AWSCDK::ECS::TaskDefinition


task_definition.add_container("container", {
    image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
    enable_restart_policy: true,
    restart_ignored_exit_codes: [0, 127],
    restart_attempt_period: AWSCDK::Duration.seconds(360),
})

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 enable_fault_injection to true.

AWSCDK::ECS::EC2TaskDefinition.new(self, "Ec2TaskDefinition", {
    enable_fault_injection: true,
})

Docker labels

You can add labels to the container with the docker_labels property or with the add_docker_label method:

task_definition = nil # AWSCDK::ECS::TaskDefinition


container = task_definition.add_container("cont", {
    image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
    memory_limit_mi_b: 1024,
    docker_labels: {
        foo: "bar",
    },
})

container.add_docker_label("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
task_definition = AWSCDK::ECS::FargateTaskDefinition.new(self, "TaskDef", {
    runtime_platform: {
        operating_system_family: AWSCDK::ECS::OperatingSystemFamily.WINDOWS_SERVER_2019_CORE,
        cpu_architecture: AWSCDK::ECS::CpuArchitecture.X86_64,
    },
    cpu: 1024,
    memory_limit_mi_b: 2048,
})

task_definition.add_container("windowsservercore", {
    logging: AWSCDK::ECS::LogDriver.aws_logs({stream_prefix: "win-iis-on-fargate"}),
    port_mappings: [{container_port: 80}],
    image: AWSCDK::ECS::ContainerImage.from_registry("mcr.microsoft.com/windows/servercore/iis:windowsservercore-ltsc2019"),
})

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.
parameter = nil # AWSCDK::SSM::IParameter
task_definition = nil # AWSCDK::ECS::TaskDefinition


# Domain-joined gMSA container from a SSM parameter
task_definition.add_container("gmsa-domain-joined-container", {
    image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
    cpu: 128,
    memory_limit_mi_b: 256,
    credential_specs: [AWSCDK::ECS::DomainJoinedCredentialSpec.from_ssm_parameter(parameter)],
})

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 = nil # AWSCDK::S3::Bucket
task_definition = nil # AWSCDK::ECS::TaskDefinition


# Domainless gMSA container from a S3 bucket object.
task_definition.add_container("gmsa-domainless-container", {
    image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
    cpu: 128,
    memory_limit_mi_b: 256,
    credential_specs: [AWSCDK::ECS::DomainlessCredentialSpec.from_s3_bucket(bucket, "credSpec")],
})

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.
task_definition = AWSCDK::ECS::FargateTaskDefinition.new(self, "TaskDef", {
    runtime_platform: {
        operating_system_family: AWSCDK::ECS::OperatingSystemFamily.LINUX,
        cpu_architecture: AWSCDK::ECS::CpuArchitecture.ARM64,
    },
    cpu: 1024,
    memory_limit_mi_b: 2048,
})

task_definition.add_container("webarm64", {
    logging: AWSCDK::ECS::LogDriver.aws_logs({stream_prefix: "graviton2-on-fargate"}),
    port_mappings: [{container_port: 80}],
    image: AWSCDK::ECS::ContainerImage.from_registry("public.ecr.aws/nginx/nginx:latest-arm64v8"),
})

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 = nil # AWSCDK::ECS::Cluster
task_definition = nil # AWSCDK::ECS::TaskDefinition


service = AWSCDK::ECS::FargateService.new(self, "Service", {
    cluster: cluster,
    task_definition: task_definition,
    desired_count: 5,
    min_healthy_percent: 100,
    circuit_breaker: {
        enable: true,
    },
})

ECS Anywhere service definition looks like:

cluster = nil # AWSCDK::ECS::Cluster
task_definition = nil # AWSCDK::ECS::TaskDefinition


service = AWSCDK::ECS::ExternalService.new(self, "Service", {
    cluster: cluster,
    task_definition: task_definition,
    desired_count: 5,
    min_healthy_percent: 100,
})

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 security_groups 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 task_definition_revision parameter:

cluster = nil # AWSCDK::ECS::Cluster
task_definition = nil # AWSCDK::ECS::TaskDefinition


AWSCDK::ECS::ExternalService.new(self, "Service", {
    cluster: cluster,
    task_definition: task_definition,
    desired_count: 5,
    min_healthy_percent: 100,
    task_definition_revision: AWSCDK::ECS::TaskDefinitionRevision.of(1),
})

AWSCDK::ECS::ExternalService.new(self, "Service", {
    cluster: cluster,
    task_definition: task_definition,
    desired_count: 5,
    min_healthy_percent: 100,
    task_definition_revision: AWSCDK::ECS::TaskDefinitionRevision.LATEST,
})

Deployment circuit breaker and rollback

Amazon ECS deployment circuit breaker automatically rolls back unhealthy service deployments, eliminating the need for manual intervention.

Use circuit_breaker 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 = nil # AWSCDK::ECS::Cluster
task_definition = nil # AWSCDK::ECS::TaskDefinition

service = AWSCDK::ECS::FargateService.new(self, "Service", {
    cluster: cluster,
    task_definition: task_definition,
    min_healthy_percent: 100,
    circuit_breaker: {
        enable: true,
        rollback: true,
    },
})

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

Deployment alarms

Amazon ECS deployment 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.

require 'aws-cdk-lib'

cluster = nil # AWSCDK::ECS::Cluster
task_definition = nil # AWSCDK::ECS::TaskDefinition
elb_alarm = nil # AWSCDK::CloudWatch::Alarm


service = AWSCDK::ECS::FargateService.new(self, "Service", {
    cluster: cluster,
    task_definition: task_definition,
    min_healthy_percent: 100,
    deployment_alarms: {
        alarm_names: [elb_alarm.alarm_name],
        behavior: AWSCDK::ECS::AlarmBehavior::ROLLBACK_ON_ALARM,
    },
})

# Defining a deployment alarm after the service has been created
cpu_alarm_name = "MyCpuMetricAlarm"
AWSCDK::CloudWatch::Alarm.new(self, "CPUAlarm", {
    alarm_name: cpu_alarm_name,
    metric: service.metric_cpu_utilization,
    evaluation_periods: 2,
    threshold: 80,
})
service.enable_deployment_alarms([cpu_alarm_name], {
    behavior: AWSCDK::ECS::AlarmBehavior::FAIL_ON_ALARM,
})

Note: Deployment alarms are only available when deployment_controller is set to DeploymentControllerType.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.

  1. 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.
  2. Define the physical name for the service. Then, don't use metric_cpu_utilization() 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:

require 'aws-cdk-lib'

cluster = nil # AWSCDK::ECS::Cluster
task_definition = nil # AWSCDK::ECS::TaskDefinition


service = AWSCDK::ECS::FargateService.new(self, "Service", {
    cluster: cluster,
    task_definition: task_definition,
})

cpu_alarm_name = "MyCpuMetricAlarm"
my_alarm = AWSCDK::CloudWatch::Alarm.new(self, "CPUAlarm", {
    alarm_name: cpu_alarm_name,
    metric: service.metric_cpu_utilization,
    evaluation_periods: 2,
    threshold: 80,
})

# Using `myAlarm.alarmName` here will cause a circular dependency
service.enable_deployment_alarms([cpu_alarm_name], {
    behavior: AWSCDK::ECS::AlarmBehavior::FAIL_ON_ALARM,
})

Option 2, defining a physical name for the service:

require 'aws-cdk-lib'

cluster = nil # AWSCDK::ECS::Cluster
task_definition = nil # AWSCDK::ECS::TaskDefinition

service_name = "MyFargateService"
service = AWSCDK::ECS::FargateService.new(self, "Service", {
    service_name: service_name,
    cluster: cluster,
    task_definition: task_definition,
    min_healthy_percent: 100,
})

cpu_metric = AWSCDK::CloudWatch::Metric.new({
    metric_name: "CPUUtilization",
    namespace: "AWS/ECS",
    period: AWSCDK::Duration.minutes(5),
    statistic: "Average",
    dimensions_map: {
        ClusterName: cluster.cluster_name,
        # Using `service.serviceName` here will cause a circular dependency
        ServiceName: service_name,
    },
})
my_alarm = AWSCDK::CloudWatch::Alarm.new(self, "CPUAlarm", {
    alarm_name: "cpuAlarmName",
    metric: cpu_metric,
    evaluation_periods: 2,
    threshold: 80,
})

service.enable_deployment_alarms([my_alarm.alarm_name], {
    behavior: AWSCDK::ECS::AlarmBehavior::FAIL_ON_ALARM,
})

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 = nil # AWSCDK::EC2::VPC
cluster = nil # AWSCDK::ECS::Cluster
task_definition = nil # AWSCDK::ECS::TaskDefinition

service = AWSCDK::ECS::FargateService.new(self, "Service", {cluster: cluster, task_definition: task_definition, min_healthy_percent: 100})

lb = AWSCDK::ElasticLoadBalancingv2::ApplicationLoadBalancer.new(self, "LB", {vpc: vpc, internet_facing: true})
listener = lb.add_listener("Listener", {port: 80})
target_group1 = listener.add_targets("ECS1", {
    port: 80,
    targets: [service],
})
target_group2 = listener.add_targets("ECS2", {
    port: 80,
    targets: [
        service.load_balancer_target({
            container_name: "MyContainer",
            container_port: 8080,
        }),
    ],
})

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

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

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

cluster = nil # AWSCDK::ECS::Cluster
task_definition = nil # AWSCDK::ECS::TaskDefinition
vpc = nil # AWSCDK::EC2::VPC

service = AWSCDK::ECS::FargateService.new(self, "Service", {cluster: cluster, task_definition: task_definition, min_healthy_percent: 100})

lb = AWSCDK::ElasticLoadBalancingv2::ApplicationLoadBalancer.new(self, "LB", {vpc: vpc, internet_facing: true})
listener = lb.add_listener("Listener", {port: 80})
service.register_load_balancer_targets({
    container_name: "web",
    container_port: 80,
    new_target_group_id: "ECS",
    listener: AWSCDK::ECS::ListenerConfig.application_listener(listener, {
        protocol: AWSCDK::ElasticLoadBalancingv2::ApplicationProtocol::HTTPS,
    }),
})

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 = nil # AWSCDK::ECS::Cluster
task_definition = nil # AWSCDK::ECS::TaskDefinition
vpc = nil # AWSCDK::EC2::VPC

service = AWSCDK::ECS::EC2Service.new(self, "Service", {cluster: cluster, task_definition: task_definition, min_healthy_percent: 100})

lb = AWSCDK::ElasticLoadBalancing::LoadBalancer.new(self, "LB", {vpc: vpc})
lb.add_listener({external_port: 80})
lb.add_target(service)

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

cluster = nil # AWSCDK::ECS::Cluster
task_definition = nil # AWSCDK::ECS::TaskDefinition
vpc = nil # AWSCDK::EC2::VPC

service = AWSCDK::ECS::EC2Service.new(self, "Service", {cluster: cluster, task_definition: task_definition, min_healthy_percent: 100})

lb = AWSCDK::ElasticLoadBalancing::LoadBalancer.new(self, "LB", {vpc: vpc})
lb.add_listener({external_port: 80})
lb.add_target(service.load_balancer_target({
    container_name: "MyContainer",
    container_port: 80,
}))

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

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 = nil # AWSCDK::EC2::VPC
cluster = nil # AWSCDK::ECS::Cluster
task_definition = nil # AWSCDK::ECS::TaskDefinition


service = AWSCDK::ECS::FargateService.new(self, "Service", {
    cluster: cluster,
    task_definition: task_definition,
    # Fargate will try to ensure an even spread of newly launched tasks across
    # all AZs corresponding to the public subnets of the VPC.
    vpc_subnets: {subnet_type: AWSCDK::EC2::SubnetType::PUBLIC},
})

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 = nil # AWSCDK::ECS::Cluster
task_definition = nil # AWSCDK::ECS::TaskDefinition


service = AWSCDK::ECS::FargateService.new(self, "Service", {
    cluster: cluster,
    task_definition: task_definition,
    availability_zone_rebalancing: AWSCDK::ECS::AvailabilityZoneRebalancing::ENABLED,
})

Availability Zone rebalancing works in the following configurations:

You can't use Availability Zone rebalancing with services that meet any of the following criteria:

Task Auto-Scaling

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

target = nil # AWSCDK::ElasticLoadBalancingv2::ApplicationTargetGroup
service = nil # AWSCDK::ECS::BaseService

scaling = service.auto_scale_task_count({max_capacity: 10})
scaling.scale_on_cpu_utilization("CpuScaling", {
    target_utilization_percent: 50,
})

scaling.scale_on_request_count("RequestScaling", {
    requests_per_target: 10000,
    target_group: target,
})

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

Integration with CloudWatch Events

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

cluster = nil # AWSCDK::ECS::Cluster

# Create a Task Definition for the container to start
task_definition = AWSCDK::ECS::EC2TaskDefinition.new(self, "TaskDef")
task_definition.add_container("TheContainer", {
    image: AWSCDK::ECS::ContainerImage.from_asset(path.resolve(__dirname, "..", "eventhandler-image")),
    memory_limit_mi_b: 256,
    logging: AWSCDK::ECS::AWSLogDriver.new({stream_prefix: "EventDemo", mode: AWSCDK::ECS::AWSLogDriverMode::NON_BLOCKING}),
})

# An Rule that describes the event trigger (in this case a scheduled run)
rule = AWSCDK::Events::Rule.new(self, "Rule", {
    schedule: AWSCDK::Events::Schedule.expression("rate(1 minute)"),
})

# Pass an environment variable to the container 'TheContainer' in the task
rule.add_target(AWSCDK::EventsTargets::ECSTask.new({
    cluster: cluster,
    task_definition: task_definition,
    task_count: 1,
    container_overrides: [
        {
            container_name: "TheContainer",
            environment: [
                {
                    name: "I_WAS_TRIGGERED",
                    value: "From CloudWatch Events",
                },
            ],
        },
    ],
}))

Log Drivers

Currently Supported Log Drivers:

awslogs Log Driver

# Create a Task Definition for the container to start
task_definition = AWSCDK::ECS::EC2TaskDefinition.new(self, "TaskDef")
task_definition.add_container("TheContainer", {
    image: AWSCDK::ECS::ContainerImage.from_registry("example-image"),
    memory_limit_mi_b: 256,
    logging: AWSCDK::ECS::LogDrivers.aws_logs({
        stream_prefix: "EventDemo",
        mode: AWSCDK::ECS::AWSLogDriverMode::NON_BLOCKING,
        max_buffer_size: AWSCDK::Size.mebibytes(25),
    }),
})

fluentd Log Driver

# Create a Task Definition for the container to start
task_definition = AWSCDK::ECS::EC2TaskDefinition.new(self, "TaskDef")
task_definition.add_container("TheContainer", {
    image: AWSCDK::ECS::ContainerImage.from_registry("example-image"),
    memory_limit_mi_b: 256,
    logging: AWSCDK::ECS::LogDrivers.fluentd,
})

gelf Log Driver

# Create a Task Definition for the container to start
task_definition = AWSCDK::ECS::EC2TaskDefinition.new(self, "TaskDef")
task_definition.add_container("TheContainer", {
    image: AWSCDK::ECS::ContainerImage.from_registry("example-image"),
    memory_limit_mi_b: 256,
    logging: AWSCDK::ECS::LogDrivers.gelf({address: "my-gelf-address"}),
})

journald Log Driver

# Create a Task Definition for the container to start
task_definition = AWSCDK::ECS::EC2TaskDefinition.new(self, "TaskDef")
task_definition.add_container("TheContainer", {
    image: AWSCDK::ECS::ContainerImage.from_registry("example-image"),
    memory_limit_mi_b: 256,
    logging: AWSCDK::ECS::LogDrivers.journald,
})

json-file Log Driver

# Create a Task Definition for the container to start
task_definition = AWSCDK::ECS::EC2TaskDefinition.new(self, "TaskDef")
task_definition.add_container("TheContainer", {
    image: AWSCDK::ECS::ContainerImage.from_registry("example-image"),
    memory_limit_mi_b: 256,
    logging: AWSCDK::ECS::LogDrivers.json_file,
})

splunk Log Driver

secret = nil # AWSCDK::ECS::Secret


# Create a Task Definition for the container to start
task_definition = AWSCDK::ECS::EC2TaskDefinition.new(self, "TaskDef")
task_definition.add_container("TheContainer", {
    image: AWSCDK::ECS::ContainerImage.from_registry("example-image"),
    memory_limit_mi_b: 256,
    logging: AWSCDK::ECS::LogDrivers.splunk({
        secret_token: secret,
        url: "my-splunk-url",
    }),
})

syslog Log Driver

# Create a Task Definition for the container to start
task_definition = AWSCDK::ECS::EC2TaskDefinition.new(self, "TaskDef")
task_definition.add_container("TheContainer", {
    image: AWSCDK::ECS::ContainerImage.from_registry("example-image"),
    memory_limit_mi_b: 256,
    logging: AWSCDK::ECS::LogDrivers.syslog,
})

firelens Log Driver

# Create a Task Definition for the container to start
task_definition = AWSCDK::ECS::EC2TaskDefinition.new(self, "TaskDef")
task_definition.add_container("TheContainer", {
    image: AWSCDK::ECS::ContainerImage.from_registry("example-image"),
    memory_limit_mi_b: 256,
    logging: AWSCDK::ECS::LogDrivers.firelens({
        options: {
            Name: "firehose",
            region: "us-west-2",
            delivery_stream: "my-stream",
        },
    }),
})

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

secret = nil # AWSCDK::SecretsManager::Secret
parameter = nil # AWSCDK::SSM::StringParameter


task_definition = AWSCDK::ECS::EC2TaskDefinition.new(self, "TaskDef")
task_definition.add_container("TheContainer", {
    image: AWSCDK::ECS::ContainerImage.from_registry("example-image"),
    memory_limit_mi_b: 256,
    logging: AWSCDK::ECS::LogDrivers.firelens({
        options: {},
        secret_options: {
             # Retrieved from AWS Secrets Manager or AWS Systems Manager Parameter Store
            apikey: AWSCDK::ECS::Secret.from_secrets_manager(secret),
            host: AWSCDK::ECS::Secret.from_ssm_parameter(parameter),
        },
    }),
})

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.

task_definition = AWSCDK::ECS::EC2TaskDefinition.new(self, "TaskDef")
task_definition.add_container("TheContainer", {
    image: AWSCDK::ECS::ContainerImage.from_registry("example-image"),
    memory_limit_mi_b: 256,
    logging: AWSCDK::ECS::LogDrivers.firelens({
        options: {
            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",
        },
    }),
})

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
task_definition = AWSCDK::ECS::EC2TaskDefinition.new(self, "TaskDef")
task_definition.add_container("TheContainer", {
    image: AWSCDK::ECS::ContainerImage.from_registry("example-image"),
    memory_limit_mi_b: 256,
    logging: AWSCDK::ECS::GenericLogDriver.new({
        log_driver: "fluentd",
        options: {
            tag: "example-tag",
        },
    }),
})

none Log Driver

The none log driver disables logging for the container (Docker none driver).

# Create a Task Definition for the container to start
task_definition = AWSCDK::ECS::EC2TaskDefinition.new(self, "TaskDef")
task_definition.add_container("TheContainer", {
    image: AWSCDK::ECS::ContainerImage.from_registry("example-image"),
    memory_limit_mi_b: 256,
    logging: AWSCDK::ECS::LogDrivers.none,
})

CloudMap Service Discovery

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

task_definition = nil # AWSCDK::ECS::TaskDefinition
cluster = nil # AWSCDK::ECS::Cluster


service = AWSCDK::ECS::EC2Service.new(self, "Service", {
    cluster: cluster,
    task_definition: task_definition,
    cloud_map_options: {
        # Create A records - useful for AWSVPC network mode.
        dns_record_type: AWSCDK::ServiceDiscovery::DNSRecordType::A,
    },
})

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:

task_definition = nil # AWSCDK::ECS::TaskDefinition
cluster = nil # AWSCDK::ECS::Cluster


# Add a container to the task definition
specific_container = task_definition.add_container("Container", {
    image: AWSCDK::ECS::ContainerImage.from_registry("/aws/aws-example-app"),
    memory_limit_mi_b: 2048,
})

# Add a port mapping
specific_container.add_port_mappings({
    container_port: 7600,
    protocol: AWSCDK::ECS::Protocol::TCP,
})

AWSCDK::ECS::EC2Service.new(self, "Service", {
    cluster: cluster,
    task_definition: task_definition,
    min_healthy_percent: 100,
    cloud_map_options: {
        # Create SRV records - useful for bridge networking
        dns_record_type: AWSCDK::ServiceDiscovery::DNSRecordType::SRV,
        # Targets port TCP port 7600 `specificContainer`
        container: specific_container,
        container_port: 7600,
    },
})

Associate With a Specific CloudMap Service

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

cloud_map_service = nil # AWSCDK::ServiceDiscovery::Service
ecs_service = nil # AWSCDK::ECS::FargateService


ecs_service.associate_cloud_map_service({
    service: cloud_map_service,
})

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 enable_fargate_capacity_providers to true when creating your cluster, or by invoking the enable_fargate_capacity_providers() method after creating your cluster. This will add both FARGATE and FARGATE_SPOT as available capacity providers on your cluster.

vpc = nil # AWSCDK::EC2::VPC


cluster = AWSCDK::ECS::Cluster.new(self, "FargateCPCluster", {
    vpc: vpc,
    enable_fargate_capacity_providers: true,
})

task_definition = AWSCDK::ECS::FargateTaskDefinition.new(self, "TaskDef")

task_definition.add_container("web", {
    image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
})

AWSCDK::ECS::FargateService.new(self, "FargateService", {
    cluster: cluster,
    task_definition: task_definition,
    min_healthy_percent: 100,
    capacity_provider_strategies: [
        {
            capacity_provider: "FARGATE_SPOT",
            weight: 2,
        },
        {
            capacity_provider: "FARGATE",
            weight: 1,
        },
    ],
})

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 enable_managed_scaling 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 enable_managed_termination_protection 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 enable_managed_termination_protection to false on 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 = nil # AWSCDK::EC2::VPC


cluster = AWSCDK::ECS::Cluster.new(self, "Cluster", {
    vpc: vpc,
})

auto_scaling_group = AWSCDK::Autoscaling::AutoScalingGroup.new(self, "ASG", {
    vpc: vpc,
    instance_type: AWSCDK::EC2::InstanceType.new("t2.micro"),
    machine_image: AWSCDK::ECS::ECSOptimizedImage.amazon_linux2,
    min_capacity: 0,
    max_capacity: 100,
})

capacity_provider = AWSCDK::ECS::AsgCapacityProvider.new(self, "AsgCapacityProvider", {
    auto_scaling_group: auto_scaling_group,
    instance_warmup_period: 300,
})
cluster.add_asg_capacity_provider(capacity_provider)

task_definition = AWSCDK::ECS::EC2TaskDefinition.new(self, "TaskDef")

task_definition.add_container("web", {
    image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
    memory_reservation_mi_b: 256,
})

AWSCDK::ECS::EC2Service.new(self, "EC2Service", {
    cluster: cluster,
    task_definition: task_definition,
    min_healthy_percent: 100,
    capacity_provider_strategies: [
        {
            capacity_provider: capacity_provider.capacity_provider_name,
            weight: 1,
        },
    ],
})

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.

Capacity Option Type provides the purchasing option for the EC2 instances used in the capacity provider. Determines whether to use On-Demand or Spot instances. Valid values are ON_DEMAND and SPOT. Defaults to ON_DEMAND when not specified. Changing this value will trigger replacement of the capacity provider. For more information, see Amazon EC2 billing and purchasing options in the Amazon EC2 User Guide.

See ECS documentation for Managed Instances Capacity Provider for more documentation.

IAM Roles Setup

Managed instances require an infrastructure and an EC2 instance profile. You can either provide your own infrastructure role and/or instance profile, or let the construct create them automatically.

Option 1: Let CDK create the role and instance profile automatically

vpc = nil # AWSCDK::EC2::VPC


cluster = AWSCDK::ECS::Cluster.new(self, "Cluster", {vpc: vpc})

security_group = AWSCDK::EC2::SecurityGroup.new(self, "SecurityGroup", {
    vpc: vpc,
    description: "Security group for managed instances",
})

mi_capacity_provider = AWSCDK::ECS::ManagedInstancesCapacityProvider.new(self, "MICapacityProvider", {
    capacity_option_type: AWSCDK::ECS::CapacityOptionType::SPOT,
    subnets: vpc.private_subnets,
    security_groups: [security_group],
    instance_requirements: {
        v_cpu_count_min: 1,
        memory_min: AWSCDK::Size.gibibytes(2),
    },
})

# Optionally configure security group rules using IConnectable interface
mi_capacity_provider.connections.allow_from(AWSCDK::EC2::Peer.ipv4(vpc.vpc_cidr_block), AWSCDK::EC2::Port.tcp(80))

# Add the capacity provider to the cluster
cluster.add_managed_instances_capacity_provider(mi_capacity_provider)

task_definition = AWSCDK::ECS::TaskDefinition.new(self, "TaskDef", {
    memory_mi_b: "512",
    cpu: "256",
    network_mode: AWSCDK::ECS::NetworkMode::AWS_VPC,
    compatibility: AWSCDK::ECS::Compatibility::MANAGED_INSTANCES,
})

task_definition.add_container("web", {
    image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
    memory_reservation_mi_b: 256,
})

AWSCDK::ECS::FargateService.new(self, "FargateService", {
    cluster: cluster,
    task_definition: task_definition,
    min_healthy_percent: 100,
    capacity_provider_strategies: [
        {
            capacity_provider: mi_capacity_provider.capacity_provider_name,
            weight: 1,
        },
    ],
})

Option 2: If you don't want to use the AmazonECSInfrastructureRolePolicyForManagedInstances managed policy for the ECS infrastructure role, you can create a custom infrastructure role with the required permissions. See documentation for what permissions are needed for the ECS infrastructure role.

You can also choose not to use the automatically created ec2InstanceProfile. See ECS documentation for what permissions are required for the profile's role.

vpc = nil # AWSCDK::EC2::VPC


cluster = AWSCDK::ECS::Cluster.new(self, "Cluster", {vpc: vpc})

# Add your custom policies to the role.
custom_instance_role = AWSCDK::IAM::Role.new(self, "CustomInstanceRole", {
    assumed_by: AWSCDK::IAM::ServicePrincipal.new("ec2.amazonaws.com"),
})

custom_instance_profile = AWSCDK::IAM::InstanceProfile.new(self, "CustomInstanceProfile", {
    role: custom_instance_role,
})

# Add your custom policies to the role.
custom_infrastructure_role = AWSCDK::IAM::Role.new(self, "CustomInfrastructureRole", {
    assumed_by: AWSCDK::IAM::ServicePrincipal.new("ecs.amazonaws.com"),
})

# Add PassRole permission to allow ECS to pass the instance role to EC2.
custom_infrastructure_role.add_to_policy(AWSCDK::IAM::PolicyStatement.new({
    effect: AWSCDK::IAM::Effect::ALLOW,
    actions: ["iam:PassRole"],
    resources: [custom_instance_role.role_arn],
    conditions: {
        StringEquals: {
            "iam:PassedToService" => "ec2.amazonaws.com",
        },
    },
}))

security_group = AWSCDK::EC2::SecurityGroup.new(self, "SecurityGroup", {
    vpc: vpc,
    description: "Security group for managed instances",
})

mi_capacity_provider_custom = AWSCDK::ECS::ManagedInstancesCapacityProvider.new(self, "MICapacityProviderCustomRoles", {
    infrastructure_role: custom_infrastructure_role,
    ec2_instance_profile: custom_instance_profile,
    subnets: vpc.private_subnets,
    security_groups: [security_group],
})

# Add the capacity provider to the cluster
cluster.add_managed_instances_capacity_provider(mi_capacity_provider_custom)

task_definition = AWSCDK::ECS::TaskDefinition.new(self, "TaskDef", {
    memory_mi_b: "512",
    cpu: "256",
    network_mode: AWSCDK::ECS::NetworkMode::AWS_VPC,
    compatibility: AWSCDK::ECS::Compatibility::MANAGED_INSTANCES,
})

task_definition.add_container("web", {
    image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
    memory_reservation_mi_b: 256,
})

AWSCDK::ECS::FargateService.new(self, "FargateService", {
    cluster: cluster,
    task_definition: task_definition,
    min_healthy_percent: 100,
    capacity_provider_strategies: [
        {
            capacity_provider: mi_capacity_provider_custom.capacity_provider_name,
            weight: 1,
        },
    ],
})

You can specify detailed instance requirements to control which types of instances are used:

vpc = nil # AWSCDK::EC2::VPC


security_group = AWSCDK::EC2::SecurityGroup.new(self, "SecurityGroup", {
    vpc: vpc,
    description: "Security group for managed instances",
})

mi_capacity_provider = AWSCDK::ECS::ManagedInstancesCapacityProvider.new(self, "MICapacityProvider", {
    subnets: vpc.private_subnets,
    security_groups: [security_group],
    instance_requirements: {
        # Required: CPU and memory constraints
        v_cpu_count_min: 2,
        v_cpu_count_max: 8,
        memory_min: AWSCDK::Size.gibibytes(4),
        memory_max: AWSCDK::Size.gibibytes(32),

        # CPU preferences
        cpu_manufacturers: [AWSCDK::EC2::CpuManufacturer::INTEL, AWSCDK::EC2::CpuManufacturer::AMD],
        instance_generations: [AWSCDK::EC2::InstanceGeneration::CURRENT],

        # Instance type filtering
        allowed_instance_types: ["m5.*", "c5.*"],

        # Performance characteristics
        burstable_performance: AWSCDK::EC2::BurstablePerformance::EXCLUDED,
        bare_metal: AWSCDK::EC2::BareMetal::EXCLUDED,

        # Accelerator requirements (for ML/AI workloads)
        accelerator_types: [AWSCDK::EC2::AcceleratorType::GPU],
        accelerator_manufacturers: [AWSCDK::EC2::AcceleratorManufacturer::NVIDIA],
        accelerator_names: [AWSCDK::EC2::AcceleratorName::T4, AWSCDK::EC2::AcceleratorName::V100],
        accelerator_count_min: 1,

        # Storage requirements
        local_storage: AWSCDK::EC2::LocalStorage::REQUIRED,
        local_storage_types: [AWSCDK::EC2::LocalStorageType::SSD],
        total_local_storage_gb_min: 100,

        # Network requirements
        network_interface_count_min: 2,
        network_bandwidth_gbps_min: 10,

        # Cost optimization
        on_demand_max_price_percentage_over_lowest_price: 10,
    },
})

Note: Service Replacement When Migrating from LaunchType to CapacityProviderStrategy

Understanding the Limitation

The ECS CreateService API does not allow specifying both launch_type and capacity_provider_strategies simultaneously. When you specify capacity_provider_strategies, 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 launch_type is immutable during updates, switching from launch_type to capacity_provider_strategies 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 = nil # AWSCDK::ECS::Cluster
task_definition = nil # AWSCDK::ECS::TaskDefinition
mi_capacity_provider = nil # AWSCDK::ECS::ManagedInstancesCapacityProvider


service = AWSCDK::ECS::FargateService.new(self, "Service", {
    cluster: cluster,
    task_definition: task_definition,
    capacity_provider_strategies: [
        {
            capacity_provider: mi_capacity_provider.capacity_provider_name,
            weight: 1,
        },
    ],
})

# Escape hatch: Force launchType at the CloudFormation level to prevent service replacement
cfn_service = service.node.default_child
cfn_service.launch_type = "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 add_default_capacity_provider_strategy. A capacity provider strategy cannot contain a mix of EC2 Autoscaling Group capacity providers and Fargate providers.

capacity_provider = nil # AWSCDK::ECS::AsgCapacityProvider


cluster = AWSCDK::ECS::Cluster.new(self, "EcsCluster", {
    enable_fargate_capacity_providers: true,
})
cluster.add_asg_capacity_provider(capacity_provider)

cluster.add_default_capacity_provider_strategy([
    {capacity_provider: "FARGATE", base: 10, weight: 50},
    {capacity_provider: "FARGATE_SPOT", weight: 50},
])
capacity_provider = nil # AWSCDK::ECS::AsgCapacityProvider


cluster = AWSCDK::ECS::Cluster.new(self, "EcsCluster", {
    enable_fargate_capacity_providers: true,
})
cluster.add_asg_capacity_provider(capacity_provider)

cluster.add_default_capacity_provider_strategy([
    {capacity_provider: capacity_provider.capacity_provider_name},
])

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 inference_accelerators field to the Ec2TaskDefinition and set the device_name and device_type properties.

inference_accelerators = [
    {
        device_name: "device1",
        device_type: "eia2.medium",
    },
]

task_definition = AWSCDK::ECS::EC2TaskDefinition.new(self, "Ec2TaskDef", {
    inference_accelerators: inference_accelerators,
})

To enable using the inference accelerators in the containers, add inference_accelerator_resources 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.

task_definition = nil # AWSCDK::ECS::TaskDefinition

inference_accelerator_resources = ["device1"]

task_definition.add_container("cont", {
    image: AWSCDK::ECS::ContainerImage.from_registry("test"),
    memory_limit_mi_b: 1024,
    inference_accelerator_resources: inference_accelerator_resources,
})

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 enable_execute_command to true in your Ec2Service, FargateService or ExternalService.

cluster = nil # AWSCDK::ECS::Cluster
task_definition = nil # AWSCDK::ECS::TaskDefinition


service = AWSCDK::ECS::EC2Service.new(self, "Service", {
    cluster: cluster,
    task_definition: task_definition,
    min_healthy_percent: 100,
    enable_execute_command: true,
})

Enabling logging

You can enable sending logs of your execute session commands to a CloudWatch log group or S3 bucket by configuring the execute_command_configuration 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 log_configuration 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 kms_key field of the execute_command_configuration. To use this key for encrypting CloudWatch log data or S3 bucket, make sure to associate the key to these resources on creation.

vpc = nil # AWSCDK::EC2::VPC

kms_key = AWSCDK::KMS::Key.new(self, "KmsKey")

# Pass the KMS key in the `encryptionKey` field to associate the key to the log group
log_group = AWSCDK::Logs::LogGroup.new(self, "LogGroup", {
    encryption_key: kms_key,
})

# Pass the KMS key in the `encryptionKey` field to associate the key to the S3 bucket
exec_bucket = AWSCDK::S3::Bucket.new(self, "EcsExecBucket", {
    encryption_key: kms_key,
})

cluster = AWSCDK::ECS::Cluster.new(self, "Cluster", {
    vpc: vpc,
    execute_command_configuration: {
        kms_key: kms_key,
        log_configuration: {
            cloud_watch_log_group: log_group,
            cloud_watch_encryption_enabled: true,
            s3_bucket: exec_bucket,
            s3_encryption_enabled: true,
            s3_key_prefix: "exec-command-output",
        },
        logging: AWSCDK::ECS::ExecuteCommandLogging::OVERRIDE,
    },
})

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 = nil # AWSCDK::ECS::Cluster
task_definition = nil # AWSCDK::ECS::TaskDefinition
container_options = nil # AWSCDK::ECS::ContainerDefinitionOptions


container = task_definition.add_container("MyContainer", container_options)

container.add_port_mappings({
    name: "api",
    container_port: 8080,
})

cluster.add_default_cloud_map_namespace({
    name: "local",
})

service = AWSCDK::ECS::FargateService.new(self, "Service", {
    cluster: cluster,
    task_definition: task_definition,
    min_healthy_percent: 100,
    service_connect_configuration: {
        services: [
            {
                port_mapping_name: "api",
                dns_name: "http-api",
                port: 80,
            },
        ],
    },
})

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 = nil # AWSCDK::ECS::Cluster
task_definition = nil # AWSCDK::ECS::TaskDefinition


service = AWSCDK::ECS::FargateService.new(self, "Service", {
    cluster: cluster,
    task_definition: task_definition,
    min_healthy_percent: 100,
})
service.enable_service_connect

Service Connect also allows custom logging, Service Discovery name, and configuration of the port where service connect traffic is received.

cluster = nil # AWSCDK::ECS::Cluster
task_definition = nil # AWSCDK::ECS::TaskDefinition


custom_service = AWSCDK::ECS::FargateService.new(self, "CustomizedService", {
    cluster: cluster,
    task_definition: task_definition,
    min_healthy_percent: 100,
    service_connect_configuration: {
        log_driver: AWSCDK::ECS::LogDrivers.aws_logs({
            stream_prefix: "sc-traffic",
        }),
        services: [
            {
                port_mapping_name: "api",
                dns_name: "customized-api",
                port: 80,
                ingress_port_override: 20040,
                discovery_name: "custom",
            },
        ],
    },
})

To set a timeout for service connect, use idle_timeout and per_request_timeout.

Note: If idle_timeout is set to a time that is less than per_request_timeout, the connection will close when the idle_timeout is reached and not the per_request_timeout.

cluster = nil # AWSCDK::ECS::Cluster
task_definition = nil # AWSCDK::ECS::TaskDefinition


service = AWSCDK::ECS::FargateService.new(self, "Service", {
    cluster: cluster,
    task_definition: task_definition,
    min_healthy_percent: 100,
    service_connect_configuration: {
        services: [
            {
                port_mapping_name: "api",
                idle_timeout: AWSCDK::Duration.minutes(5),
                per_request_timeout: AWSCDK::Duration.minutes(5),
            },
        ],
    },
})

Visit Amazon ECS support for configurable timeout for services running with Service Connect for more details.

Service Connect Access Logs

Service Connect access logs provide detailed telemetry about individual requests processed by the Service Connect proxy, including HTTP methods, paths, response codes, and timing information. These logs complement application logs by capturing per-request traffic metadata.

cluster = nil # AWSCDK::ECS::Cluster
task_definition = nil # AWSCDK::ECS::TaskDefinition


service = AWSCDK::ECS::FargateService.new(self, "Service", {
    cluster: cluster,
    task_definition: task_definition,
    service_connect_configuration: {
        services: [
            {
                port_mapping_name: "api",
            },
        ],
        access_log_configuration: {
            format: AWSCDK::ECS::ServiceConnectAccessLogFormat::JSON,
            include_query_parameters: true,
        },
        # When configuring access log,
        # you also need to configure the log driver accordingly.
        log_driver: AWSCDK::ECS::LogDrivers.aws_logs({
            stream_prefix: "prefix",
        }),
    },
})

The format option determines the format of the access log output:

The include_query_parameters option specifies whether to include query parameters in the access logs. When enabled, query parameters from HTTP requests are included in the logs. Consider security and privacy implications, as query parameters may contain sensitive information such as request IDs and tokens. By default, this parameter is false.

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 kms_key_id.

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 = nil # AWSCDK::ECS::Cluster

task_definition = AWSCDK::ECS::FargateTaskDefinition.new(self, "TaskDef")

container = task_definition.add_container("web", {
    image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
    port_mappings: [
        {
            container_port: 80,
            protocol: AWSCDK::ECS::Protocol::TCP,
        },
    ],
})

volume = AWSCDK::ECS::ServiceManagedVolume.new(self, "EBSVolume", {
    name: "ebs1",
    managed_ebs_volume: {
        size: AWSCDK::Size.gibibytes(15),
        volume_type: AWSCDK::EC2::EbsDeviceVolumeType::GP3,
        file_system_type: AWSCDK::ECS::FileSystemType::XFS,
        tag_specifications: [
            {
                tags: {
                    purpose: "production",
                },
                propagate_tags: AWSCDK::ECS::EbsPropagatedTagSource::SERVICE,
            },
        ],
    },
})

volume.mount_in(container, {
    container_path: "/var/lib",
    read_only: false,
})

task_definition.add_volume(volume)

service = AWSCDK::ECS::FargateService.new(self, "FargateService", {
    cluster: cluster,
    task_definition: task_definition,
    min_healthy_percent: 100,
})

service.add_volume(volume)

To create an EBS volume from an existing snapshot by specifying the snap_shot_id while adding a volume to the service.

container = nil # AWSCDK::ECS::ContainerDefinition
cluster = nil # AWSCDK::ECS::Cluster
task_definition = nil # AWSCDK::ECS::TaskDefinition


volume_from_snapshot = AWSCDK::ECS::ServiceManagedVolume.new(self, "EBSVolume", {
    name: "nginx-vol",
    managed_ebs_volume: {
        snap_shot_id: "snap-066877671789bd71b",
        volume_type: AWSCDK::EC2::EbsDeviceVolumeType::GP3,
        file_system_type: AWSCDK::ECS::FileSystemType::XFS,
        # Specifies the Amazon EBS Provisioned Rate for Volume Initialization.
        # Valid range is between 100 and 300 MiB/s.
        volume_initialization_rate: AWSCDK::Size.mebibytes(200),
    },
})

volume_from_snapshot.mount_in(container, {
    container_path: "/var/lib",
    read_only: false,
})
task_definition.add_volume(volume_from_snapshot)
service = AWSCDK::ECS::FargateService.new(self, "FargateService", {
    cluster: cluster,
    task_definition: task_definition,
    min_healthy_percent: 100,
})

service.add_volume(volume_from_snapshot)

Enable pseudo-terminal (TTY) allocation

You can allocate a pseudo-terminal (TTY) for a container passing pseudo_terminal 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.

task_definition = AWSCDK::ECS::EC2TaskDefinition.new(self, "TaskDef")
task_definition.add_container("TheContainer", {
    image: AWSCDK::ECS::ContainerImage.from_registry("example-image"),
    pseudo_terminal: true,
})

Disable service container image version consistency

You can disable the container image "version consistency" feature of ECS service deployments on a per-container basis.

task_definition = AWSCDK::ECS::EC2TaskDefinition.new(self, "TaskDef")
task_definition.add_container("TheContainer", {
    image: AWSCDK::ECS::ContainerImage.from_registry("example-image"),
    version_consistency: AWSCDK::ECS::VersionConsistency::DISABLED,
})

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.

task_definition = AWSCDK::ECS::EC2TaskDefinition.new(self, "TaskDef")
task_definition.add_container("TheContainer", {
    image: AWSCDK::ECS::ContainerImage.from_registry("example-image"),
    ulimits: [
        {
            hard_limit: 128,
            name: AWSCDK::ECS::UlimitName::RSS,
            soft_limit: 128,
        },
    ],
})

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 service_connect_configuration property.

The tls property is an object with the following properties:

cluster = nil # AWSCDK::ECS::Cluster
task_definition = nil # AWSCDK::ECS::TaskDefinition
kms_key = nil # AWSCDK::KMS::IKey
role = nil # AWSCDK::IAM::IRole


service = AWSCDK::ECS::FargateService.new(self, "FargateService", {
    cluster: cluster,
    task_definition: task_definition,
    service_connect_configuration: {
        services: [
            {
                tls: {
                    role: role,
                    kms_key: kms_key,
                    aws_pca_authority_arn: "arn:aws:acm-pca:us-east-1:123456789012:certificate-authority/123456789012",
                },
                port_mapping_name: "api",
            },
        ],
        namespace: "sample namespace",
    },
})

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

require 'aws-cdk-lib'

cluster = nil # AWSCDK::ECS::Cluster
task_definition = nil # AWSCDK::ECS::TaskDefinition
lambda_hook = nil # AWSCDK::Lambda::Function
blue_target_group = nil # AWSCDK::ElasticLoadBalancingv2::ApplicationTargetGroup
green_target_group = nil # AWSCDK::ElasticLoadBalancingv2::ApplicationTargetGroup
prod_listener_rule = nil # AWSCDK::ElasticLoadBalancingv2::ApplicationListenerRule


service = AWSCDK::ECS::FargateService.new(self, "Service", {
    cluster: cluster,
    task_definition: task_definition,
    deployment_strategy: AWSCDK::ECS::DeploymentStrategy::BLUE_GREEN,
})

service.add_lifecycle_hook(AWSCDK::ECS::DeploymentLifecycleLambdaTarget.new(lambda_hook, "PreScaleHook", {
    lifecycle_stages: [AWSCDK::ECS::DeploymentLifecycleStage::PRE_SCALE_UP],
}))

target = service.load_balancer_target({
    container_name: "nginx",
    container_port: 80,
    protocol: AWSCDK::ECS::Protocol::TCP,
    alternate_target: AWSCDK::ECS::AlternateTarget.new("AlternateTarget", {
        alternate_target_group: green_target_group,
        production_listener: AWSCDK::ECS::ListenerRuleConfiguration.application_listener_rule(prod_listener_rule),
    }),
})

target.attach_to_application_target_group(blue_target_group)

Buil-in Linear and Canary Deployments

Amazon ECS supports progressive deployment strategies that allow you to validate new service revisions before shifting all production traffic. Both strategies require an Application Load Balancer (ALB) with target groups for traffic routing.

Linear Deployment

Linear deployment strategy shifts production traffic in equal percentage increments with configurable wait times between each step:

cluster = nil # AWSCDK::ECS::Cluster
task_definition = nil # AWSCDK::ECS::TaskDefinition
blue_target_group = nil # AWSCDK::ElasticLoadBalancingv2::ApplicationTargetGroup
green_target_group = nil # AWSCDK::ElasticLoadBalancingv2::ApplicationTargetGroup
prod_listener_rule = nil # AWSCDK::ElasticLoadBalancingv2::ApplicationListenerRule


service = AWSCDK::ECS::FargateService.new(self, "Service", {
    cluster: cluster,
    task_definition: task_definition,
    deployment_strategy: AWSCDK::ECS::DeploymentStrategy::LINEAR,
    linear_configuration: {
        step_percent: 10,
        step_bake_time: AWSCDK::Duration.minutes(5),
    },
})

target = service.load_balancer_target({
    container_name: "web",
    container_port: 80,
    alternate_target: AWSCDK::ECS::AlternateTarget.new("AlternateTarget", {
        alternate_target_group: green_target_group,
        production_listener: AWSCDK::ECS::ListenerRuleConfiguration.application_listener_rule(prod_listener_rule),
    }),
})

target.attach_to_application_target_group(blue_target_group)

Valid values:

Canary Deployment

Canary deployment strategy shifts a fixed percentage of traffic to the new service revision for testing, then shifts the remaining traffic after a bake period:

cluster = nil # AWSCDK::ECS::Cluster
task_definition = nil # AWSCDK::ECS::TaskDefinition
blue_target_group = nil # AWSCDK::ElasticLoadBalancingv2::ApplicationTargetGroup
green_target_group = nil # AWSCDK::ElasticLoadBalancingv2::ApplicationTargetGroup
prod_listener_rule = nil # AWSCDK::ElasticLoadBalancingv2::ApplicationListenerRule


service = AWSCDK::ECS::FargateService.new(self, "Service", {
    cluster: cluster,
    task_definition: task_definition,
    deployment_strategy: AWSCDK::ECS::DeploymentStrategy::CANARY,
    canary_configuration: {
        step_percent: 5,
        step_bake_time: AWSCDK::Duration.minutes(10),
    },
})

target = service.load_balancer_target({
    container_name: "web",
    container_port: 80,
    alternate_target: AWSCDK::ECS::AlternateTarget.new("AlternateTarget", {
        alternate_target_group: green_target_group,
        production_listener: AWSCDK::ECS::ListenerRuleConfiguration.application_listener_rule(prod_listener_rule),
    }),
})

target.attach_to_application_target_group(blue_target_group)

Valid values:

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 = nil # AWSCDK::ECS::Cluster
task_definition = nil # AWSCDK::ECS::TaskDefinition


AWSCDK::ECS::EC2Service.new(self, "Ec2Service", {
    cluster: cluster,
    task_definition: task_definition,
    daemon: true,
})

AWSCDK::ECS::ExternalService.new(self, "ExternalService", {
    cluster: cluster,
    task_definition: task_definition,
    daemon: true,
})

Force New Deployment

You can force a new deployment of a service without changing the task definition or desired count. This is useful when you want ECS to pull the latest container image with the same tag or to trigger a redeployment.

When called without a nonce, a timestamp is generated automatically. This means every cdk synth produces a different template and every cdk deploy triggers a new deployment, regardless of whether any code has changed. To control when deployments happen, provide a stable nonce that only changes when you intentionally want to redeploy (e.g., an image digest or a version string).

cluster = nil # AWSCDK::ECS::Cluster
task_definition = nil # AWSCDK::ECS::TaskDefinition


service = AWSCDK::ECS::FargateService.new(self, "Service", {
    cluster: cluster,
    task_definition: task_definition,
})

# Force a new deployment with an auto-generated nonce (deploys on every `cdk deploy`)
service.force_new_deployment

# Or provide your own nonce to control when deployments are triggered
service.force_new_deployment("my-custom-nonce-v2")

Alternatively, you can configure force_new_deployment declaratively as a constructor option. This approach also allows you to explicitly disable the feature with enabled: false.

cluster = nil # AWSCDK::ECS::Cluster
task_definition = nil # AWSCDK::ECS::TaskDefinition


# Force a new deployment on every `cdk deploy` by using a time-based nonce
service = AWSCDK::ECS::FargateService.new(self, "Service", {
    cluster: cluster,
    task_definition: task_definition,
    force_new_deployment: {
        enabled: true,
        nonce: Date[:now].to_string,
    },
})

Calling the force_new_deployment() method takes precedence over the constructor option. The nonce passed to the method (or the auto-generated one when none is provided) overrides any value configured through the force_new_deployment property.

Mixins

ECS provides mixins that can be applied to L1 and L2 constructs.

ClusterSettings

Applies one or more cluster settings to an ECS cluster. If a setting with the same name already exists, its value is replaced:

AWSCDK::ECS::CfnCluster.new(self, "Cluster").with(AWSCDK::ECS::Mixins::ClusterSettings.new([{name: "containerInsights", value: "enhanced"}]))

API Reference

Namespaces 1

Mixins

Classes 69

AlternateTargetConfiguration for alternate target groups used in blue/green deployments with load balance AppMeshProxyConfigurationThe class for App Mesh proxy configurations. AppProtocolService connect app protocol. AsgCapacityProviderAn Auto Scaling Group Capacity Provider. AssetEnvironmentFileEnvironment file from a local directory. AssetImageAn image that will be built from a local directory with a Dockerfile. AWSLogDriverA log driver that sends log information to CloudWatch Logs. BaseServiceThe base class for Ec2Service and FargateService services. BottleRocketImageConstruct an Bottlerocket image from the latest AMI published in SSM. BuiltInAttributesThe built-in container instance attributes. CfnCapacityProviderCreates a capacity provider. CfnClusterThe `AWS::ECS::Cluster` resource creates an Amazon Elastic Container Service (Amazon ECS) CfnClusterCapacityProviderAssociationsThe `AWS::ECS::ClusterCapacityProviderAssociations` resource associates one or more capaci CfnDaemonInformation about a daemon resource. CfnDaemonTaskDefinitionThe details of a daemon task definition. CfnExpressGatewayServiceCreates an Express service that simplifies deploying containerized web applications on Ama CfnPrimaryTaskSetModifies which task set in a service is the primary task set. CfnServiceThe `AWS::ECS::Service` resource creates an Amazon Elastic Container Service (Amazon ECS) CfnTaskDefinitionRegisters a new task definition from the supplied `family` and `containerDefinitions` . CfnTaskSetCreate a task set in the specified cluster and service. ClusterA regional grouping of one or more container instances on which you can run tasks and serv ClusterGrantsCollection of grant methods for a IClusterRef. ContainerDefinitionA container definition is used in a task definition to describe the containers that are la ContainerImageConstructs for types of container images. CpuArchitectureThe CpuArchitecture for Fargate Runtime Platform. CredentialSpecBase construct for a credential specification (CredSpec). DeploymentLifecycleLambdaTargetUse an AWS Lambda function as a deployment lifecycle hook target. DomainJoinedCredentialSpecCredential specification (CredSpec) file. DomainlessCredentialSpecCredential specification for domainless gMSA. EC2ServiceThis creates a service using the EC2 launch type on an ECS cluster. EC2TaskDefinitionThe details of a task definition run on an EC2 cluster. ECRImageAn image from an Amazon ECR repository. ECSOptimizedImageConstruct a Linux or Windows machine image from the latest ECS Optimized AMI published in EnvironmentFileConstructs for types of environment files. ExternalServiceThis creates a service using the External launch type on an ECS cluster. ExternalTaskDefinitionThe details of a task definition run on an External cluster. FargateServiceThis creates a service using the Fargate launch type on an ECS cluster. FargateTaskDefinitionThe details of a task definition run on a Fargate cluster. FireLensLogDriverFireLens enables you to use task definition parameters to route logs to an AWS service or FirelensLogRouterFirelens log router. FluentdLogDriverA log driver that sends log information to journald Logs. GelfLogDriverA log driver that sends log information to journald Logs. GenericLogDriverA log driver that sends logs to the specified driver. JournaldLogDriverA log driver that sends log information to journald Logs. JsonFileLogDriverA log driver that sends log information to json-file Logs. LinuxParametersLinux-specific options that are applied to the container. ListenerConfigBase class for configuring listener when registering targets. ListenerRuleConfigurationRepresents a listener configuration for advanced load balancer settings. LogDriverThe base class for log drivers. LogDriversThe base class for log drivers. ManagedInstancesCapacityProviderA Managed Instances Capacity Provider. NoneLogDriverA log driver that sets the log driver to `none` (no logs collected). OperatingSystemFamilyThe operating system for Fargate Runtime Platform. PlacementConstraintThe placement constraints to use for tasks in the service. For more information, see [Amaz PlacementStrategyThe placement strategies to use for tasks in the service. For more information, see [Amazo PortMapPortMap ValueObjectClass having by ContainerDefinition. ProxyConfigurationThe base class for proxy configurations. ProxyConfigurationsThe base class for proxy configurations. RepositoryImageAn image hosted in a public or private repository. S3EnvironmentFileEnvironment file from S3. ScalableTaskCountThe scalable attribute representing task count. SecretA secret environment variable. ServiceConnectServiceConnect ValueObjectClass having by ContainerDefinition. ServiceManagedVolumeRepresents a service-managed volume and always configured at launch. SplunkLogDriverA log driver that sends log information to splunk Logs. SyslogLogDriverA log driver that sends log information to syslog Logs. TagParameterContainerImageA special type of `ContainerImage` that uses an ECR repository for the image, but a CloudF TaskDefinitionThe base class for all task definitions. TaskDefinitionRevisionRepresents revision of a task definition, either a specific numbered revision or the `late

Interfaces 127

AddAutoScalingGroupCapacityOptionsThe properties for adding an AutoScalingGroup. AddCapacityOptionsThe properties for adding instance capacity to an AutoScalingGroup. AlternateTargetConfigConfiguration returned by AlternateTargetConfiguration.bind(). AlternateTargetOptionsOptions for AlternateTarget configuration. AlternateTargetPropsProperties for AlternateTarget configuration. AppMeshProxyConfigurationConfigPropsThe configuration to use when setting an App Mesh proxy configuration. AppMeshProxyConfigurationPropsInterface for setting the properties of proxy configuration. AsgCapacityProviderPropsThe options for creating an Auto Scaling Group Capacity Provider. AssetImagePropsThe properties for building an AssetImage. AssociateCloudMapServiceOptionsThe options for using a cloudmap service. AuthorizationConfigThe authorization configuration details for the Amazon EFS file system. AWSLogDriverPropsSpecifies the awslogs log driver configuration options. BaseLogDriverProps BaseMountPointThe base details of where a volume will be mounted within a container. BaseServiceOptionsThe properties for the base Ec2Service or FargateService service. BaseServicePropsComplete base service properties that are required to be supplied by the implementation of BottleRocketImagePropsProperties for BottleRocketImage. CapacityProviderStrategyA Capacity Provider strategy to use for the service. CfnCapacityProviderPropsProperties for defining a `CfnCapacityProvider`. CfnClusterCapacityProviderAssociationsPropsProperties for defining a `CfnClusterCapacityProviderAssociations`. CfnClusterPropsProperties for defining a `CfnCluster`. CfnDaemonPropsProperties for defining a `CfnDaemon`. CfnDaemonTaskDefinitionPropsProperties for defining a `CfnDaemonTaskDefinition`. CfnExpressGatewayServicePropsProperties for defining a `CfnExpressGatewayService`. CfnPrimaryTaskSetPropsProperties for defining a `CfnPrimaryTaskSet`. CfnServicePropsProperties for defining a `CfnService`. CfnTaskDefinitionPropsProperties for defining a `CfnTaskDefinition`. CfnTaskSetPropsProperties for defining a `CfnTaskSet`. CloudMapNamespaceOptionsThe options for creating an AWS Cloud Map namespace. CloudMapOptionsThe options to enabling AWS Cloud Map for an Amazon ECS service. ClusterAttributesThe properties to import from the ECS cluster. ClusterPropsThe properties used to define an ECS cluster. CommonTaskDefinitionAttributesThe common task definition attributes used across all types of task definitions. CommonTaskDefinitionPropsThe common properties for all task definitions. ContainerDefinitionOptions ContainerDefinitionPropsThe properties in a container definition. ContainerDependencyThe details of a dependency on another container in the task definition. ContainerImageConfigThe configuration for creating a container image. ContainerMountPointDefines the mount point details for attaching a volume to a container. CpuUtilizationScalingPropsThe properties for enabling scaling based on CPU utilization. CredentialSpecConfigConfiguration for a credential specification (CredSpec) used for a ECS container. DeploymentAlarmConfigConfiguration for deployment alarms. DeploymentAlarmOptionsOptions for deployment alarms. DeploymentCircuitBreakerThe deployment circuit breaker to use for the service. DeploymentControllerThe deployment controller to use for the service. DeploymentLifecycleHookTargetConfigConfiguration for a deployment lifecycle hook target. DeploymentLifecycleLambdaTargetPropsConfiguration for a lambda deployment lifecycle hook. DeviceA container instance host device. DockerVolumeConfigurationThe configuration for a Docker volume. EBSTagSpecificationTag Specification for EBS volume. EC2ServiceAttributesThe properties to import from the service using the EC2 launch type. EC2ServicePropsThe properties for defining a service using the EC2 launch type. EC2TaskDefinitionAttributesAttributes used to import an existing EC2 task definition. EC2TaskDefinitionPropsThe properties for a task definition run on an EC2 cluster. ECSOptimizedImageOptionsAdditional configuration properties for EcsOptimizedImage factory functions. ECSTarget EFSVolumeConfigurationThe configuration for an Elastic FileSystem volume. EnvironmentFileConfigConfiguration for the environment file. ExecuteCommandConfigurationThe details of the execute command configuration. ExecuteCommandLogConfigurationThe log configuration for the results of the execute command actions. ExternalServiceAttributesThe properties to import from the service using the External launch type. ExternalServicePropsThe properties for defining a service using the External launch type. ExternalTaskDefinitionAttributesAttributes used to import an existing External task definition. ExternalTaskDefinitionPropsThe properties for a task definition run on an External cluster. FargateServiceAttributesThe properties to import from the service using the Fargate launch type. FargateServicePropsThe properties for defining a service using the Fargate launch type. FargateTaskDefinitionAttributesAttributes used to import an existing Fargate task definition. FargateTaskDefinitionPropsThe properties for a task definition. FirelensConfigFirelens Configuration https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_f FireLensLogDriverPropsSpecifies the firelens log driver configuration options. FirelensLogRouterDefinitionOptionsThe options for creating a firelens log router. FirelensLogRouterPropsThe properties in a firelens log router. FirelensOptionsThe options for firelens log router https://docs.aws.amazon.com/AmazonECS/latest/developer FluentdLogDriverPropsSpecifies the fluentd log driver configuration options. ForceNewDeploymentConfiguration for forcing a new deployment of the service. GelfLogDriverPropsSpecifies the journald log driver configuration options. GenericLogDriverPropsThe configuration to use when creating a log driver. HealthCheckThe health check command and associated configuration parameters for the container. HostThe details on a container instance bind mount host volume. IAlternateTargetInterface for configuring alternate target groups for blue/green deployments. IBaseServiceThe interface for BaseService. IClusterA regional grouping of one or more container instances on which you can run tasks and serv IDeploymentLifecycleHookTargetInterface for deployment lifecycle hook targets. IEC2ServiceThe interface for a service using the EC2 launch type on an ECS cluster. IEC2TaskDefinitionThe interface of a task definition run on an EC2 cluster. IECSLoadBalancerTargetInterface for ECS load balancer target. IExternalServiceThe interface for a service using the External launch type on an ECS cluster. IExternalTaskDefinitionThe interface of a task definition run on an External cluster. IFargateServiceThe interface for a service using the Fargate launch type on an ECS cluster. IFargateTaskDefinitionThe interface of a task definition run on a Fargate cluster. InferenceAcceleratorElastic Inference Accelerator. IServiceThe interface for a service. ITaskDefinitionThe interface for all task definitions. ITaskDefinitionExtensionAn extension for Task Definitions. JournaldLogDriverPropsSpecifies the journald log driver configuration options. JsonFileLogDriverPropsSpecifies the json-file log driver configuration options. LinuxParametersPropsThe properties for defining Linux-specific options that are applied to the container. LoadBalancerTargetOptionsProperties for defining an ECS target. LogDriverConfigThe configuration to use when creating a log driver. ManagedInstancesCapacityProviderPropsThe options for creating a Managed Instances Capacity Provider. ManagedStorageConfigurationKms Keys for encryption ECS managed storage. MemoryUtilizationScalingPropsThe properties for enabling scaling based on memory utilization. MountPointThe details of data volume mount points for a container. PortMappingPort mappings allow containers to access ports on the host container instance to send or r RepositoryImagePropsThe properties for an image hosted in a public or private repository. RequestCountScalingPropsThe properties for enabling scaling based on Application Load Balancer (ALB) request count RuntimePlatformThe interface for Runtime Platform. ScalableTaskCountPropsThe properties of a scalable attribute representing task count. ScratchSpaceThe temporary disk space mounted to the container. SecretVersionInfoSpecify the secret's version id or version stage. ServiceConnectAccessLogConfigurationConfiguration for Service Connect access logs. ServiceConnectPropsInterface for Service Connect configuration. ServiceConnectServiceInterface for service connect Service props. ServiceConnectTLSConfigurationTLS configuration for Service Connect service. ServiceManagedEBSVolumeConfigurationRepresents the configuration for an ECS Service managed EBS volume. ServiceManagedVolumePropsRepresents the Volume configuration for an ECS service. SplunkLogDriverPropsSpecifies the splunk log driver configuration options. SyslogLogDriverPropsSpecifies the syslog log driver configuration options. SystemControlKernel parameters to set in the container. TaskDefinitionAttributesA reference to an existing task definition. TaskDefinitionPropsThe properties for task definitions. TmpfsThe details of a tmpfs mount for a container. TrackCustomMetricPropsThe properties for enabling target tracking scaling based on a custom CloudWatch metric. TrafficShiftConfigConfiguration for traffic shift during progressive deployments. UlimitThe ulimit settings to pass to the container. VolumeA data volume used in a task definition. VolumeFromThe details on a data volume from another container in the same task definition.

Enums 39

AlarmBehaviorDeployment behavior when an ECS Service Deployment Alarm is triggered. AmiHardwareTypeThe ECS-optimized AMI variant to use. AvailabilityZoneRebalancingIndicates whether to use Availability Zone rebalancing for an ECS service. AWSLogDriverModeawslogs provides two modes for delivering messages from the container to the log driver. BinPackResourceInstance resource used for bin packing. BottlerocketECSVariantAmazon ECS variant. CapabilityA Linux capability. CapacityOptionTypeThe capacity option type for instances launched by a Managed Instances Capacity Provider. CompatibilityThe task launch type compatibility requirement. ContainerDependencyCondition ContainerInsightsThe CloudWatch Container Insights setting. DeploymentControllerTypeThe deployment controller type to use for the service. DeploymentLifecycleStageDeployment lifecycle stages where hooks can be executed. DeploymentStrategyThe deployment stratergy to use for ECS controller. DevicePermissionPermissions for device access. EbsPropagatedTagSourcePropagate tags for EBS Volume Configuration from either service or task definition. EnvironmentFileTypeType of environment file to be included in the container definition. ExecuteCommandLoggingThe log settings to use to for logging the execute command session. FargatePlatformVersionThe platform version on which to run your service. FileSystemTypeFileSystemType for Service Managed EBS Volume Configuration. FirelensConfigFileTypeFirelens configuration file type, s3 or file path. FirelensLogRouterTypeFirelens log router type, fluentbit or fluentd. GelfCompressionTypeThe type of compression the GELF driver uses to compress each log message. InstanceMonitoringThe monitoring configuration for EC2 instances. IpcModeThe IPC resource namespace to use for the containers in the task. LaunchTypeThe launch type of an ECS service. MachineImageTypeThe machine image type. NetworkModeThe networking mode to use for the containers in the task. PidModeThe process namespace to use for the containers in the task. PropagatedTagSourcePropagate tags from either service or task definition. PropagateManagedInstancesTagsPropagate tags for Managed Instances. ProtocolNetwork protocol. ScopeThe scope for the Docker volume that determines its lifecycle. ServiceConnectAccessLogFormatThe format of Service Connect access logs. SplunkLogFormatLog Message Format. TmpfsMountOptionThe supported options for a tmpfs mount for a container. UlimitNameType of resource to set a limit on. VersionConsistencyState of the container version consistency feature. WindowsOptimizedVersionECS-optimized Windows version list.