Skip to content
v2.274.0

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:

ts
declare const vpc: ec2.Vpc;

// Create an ECS cluster
const cluster = new ecs.Cluster(this, 'Cluster', { vpc });

// Add capacity to it
cluster.addCapacity('DefaultAutoScalingGroupCapacity', {
  instanceType: new ec2.InstanceType("t2.xlarge"),
});

const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');

taskDefinition.addContainer('DefaultContainer', {
  image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  memoryLimitMiB: 512,
});

// Instantiate an Amazon ECS Service
const ecsService = new ecs.Ec2Service(this, 'Service', {
  cluster,
  taskDefinition,
  minHealthyPercent: 100,
  circuitBreaker: {
    enable: true,
  },
});
python
# vpc: ec2.Vpc


# Create an ECS cluster
cluster = ecs.Cluster(self, "Cluster", vpc=vpc)

# Add capacity to it
cluster.add_capacity("DefaultAutoScalingGroupCapacity",
    instance_type=ec2.InstanceType("t2.xlarge")
)

task_definition = ecs.Ec2TaskDefinition(self, "TaskDef")

task_definition.add_container("DefaultContainer",
    image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample"),
    memory_limit_mi_b=512
)

# Instantiate an Amazon ECS Service
ecs_service = ecs.Ec2Service(self, "Service",
    cluster=cluster,
    task_definition=task_definition,
    min_healthy_percent=100,
    circuit_breaker=ecs.DeploymentCircuitBreaker(
        enable=True
    )
)
java
Vpc vpc;


// Create an ECS cluster
Cluster cluster = Cluster.Builder.create(this, "Cluster").vpc(vpc).build();

// Add capacity to it
cluster.addCapacity("DefaultAutoScalingGroupCapacity", AddCapacityOptions.builder()
        .instanceType(new InstanceType("t2.xlarge"))
        .build());

Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");

taskDefinition.addContainer("DefaultContainer", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
        .memoryLimitMiB(512)
        .build());

// Instantiate an Amazon ECS Service
Ec2Service ecsService = Ec2Service.Builder.create(this, "Service")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .minHealthyPercent(100)
        .circuitBreaker(DeploymentCircuitBreaker.builder()
                .enable(true)
                .build())
        .build();
csharp
Vpc vpc;


// Create an ECS cluster
var cluster = new Cluster(this, "Cluster", new ClusterProps { Vpc = vpc });

// Add capacity to it
cluster.AddCapacity("DefaultAutoScalingGroupCapacity", new AddCapacityOptions {
    InstanceType = new InstanceType("t2.xlarge")
});

var taskDefinition = new Ec2TaskDefinition(this, "TaskDef");

taskDefinition.AddContainer("DefaultContainer", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
    MemoryLimitMiB = 512
});

// Instantiate an Amazon ECS Service
var ecsService = new Ec2Service(this, "Service", new Ec2ServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    MinHealthyPercent = 100,
    CircuitBreaker = new DeploymentCircuitBreaker {
        Enable = true
    }
});
go
var vpc Vpc


// Create an ECS cluster
cluster := ecs.NewCluster(this, jsii.String("Cluster"), &ClusterProps{
	Vpc: Vpc,
})

// Add capacity to it
cluster.AddCapacity(jsii.String("DefaultAutoScalingGroupCapacity"), &AddCapacityOptions{
	InstanceType: ec2.NewInstanceType(jsii.String("t2.xlarge")),
})

taskDefinition := ecs.NewEc2TaskDefinition(this, jsii.String("TaskDef"))

taskDefinition.AddContainer(jsii.String("DefaultContainer"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	MemoryLimitMiB: jsii.Number(512),
})

// Instantiate an Amazon ECS Service
ecsService := ecs.NewEc2Service(this, jsii.String("Service"), &Ec2ServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	MinHealthyPercent: jsii.Number(100),
	CircuitBreaker: &DeploymentCircuitBreaker{
		Enable: jsii.Boolean(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:

  • Use the Ec2TaskDefinition and Ec2Service constructs to run tasks on Amazon EC2 instances running in your account.
  • Use the FargateTaskDefinition and FargateService constructs to run tasks on instances that are managed for you by AWS.
  • Use the ExternalTaskDefinition and ExternalService constructs to run AWS ECS Anywhere tasks on self-managed infrastructure.

Here are the main differences:

  • Amazon EC2: instances are under your control. Complete control of task to host allocation. Required to specify at least a memory reservation or limit for every container. Can use Host, Bridge and AwsVpc networking modes. Can attach Classic Load Balancer. Can share volumes between container and host.
  • AWS Fargate: tasks run on AWS-managed instances, AWS manages task to host allocation for you. Requires specification of memory and cpu sizes at the taskdefinition level. Only supports AwsVpc networking modes and Application/Network Load Balancers. Only the AWS log driver is supported. Many host features are not supported such as adding kernel capabilities and mounting host devices/volumes inside the container.
  • AWS ECS Anywhere: tasks are run and managed by AWS ECS Anywhere on infrastructure owned by the customer. Bridge, Host and None networking modes are supported. Does not support autoscaling, load balancing, cloudmap or attachment of volumes.

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

Clusters ​

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

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

ts
declare const vpc: ec2.Vpc;

const cluster = new ecs.Cluster(this, 'Cluster', {
  vpc,
});
python
# vpc: ec2.Vpc


cluster = ecs.Cluster(self, "Cluster",
    vpc=vpc
)
java
Vpc vpc;


Cluster cluster = Cluster.Builder.create(this, "Cluster")
        .vpc(vpc)
        .build();
csharp
Vpc vpc;


var cluster = new Cluster(this, "Cluster", new ClusterProps {
    Vpc = vpc
});
go
var vpc Vpc


cluster := ecs.NewCluster(this, jsii.String("Cluster"), &ClusterProps{
	Vpc: Vpc,
})

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

ts
declare const key: kms.Key;

const cluster = new ecs.Cluster(this, 'Cluster', {
  managedStorageConfiguration: {
    fargateEphemeralStorageKmsKey: key,
    kmsKey: key,
  },
});
python
# key: kms.Key


cluster = ecs.Cluster(self, "Cluster",
    managed_storage_configuration=ecs.ManagedStorageConfiguration(
        fargate_ephemeral_storage_kms_key=key,
        kms_key=key
    )
)
java
Key key;


Cluster cluster = Cluster.Builder.create(this, "Cluster")
        .managedStorageConfiguration(ManagedStorageConfiguration.builder()
                .fargateEphemeralStorageKmsKey(key)
                .kmsKey(key)
                .build())
        .build();
csharp
Key key;


var cluster = new Cluster(this, "Cluster", new ClusterProps {
    ManagedStorageConfiguration = new ManagedStorageConfiguration {
        FargateEphemeralStorageKmsKey = key,
        KmsKey = key
    }
});
go
var key Key


cluster := ecs.NewCluster(this, jsii.String("Cluster"), &ClusterProps{
	ManagedStorageConfiguration: &ManagedStorageConfiguration{
		FargateEphemeralStorageKmsKey: key,
		KmsKey: 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.

ts
const clusterArn = 'arn:aws:ecs:us-east-1:012345678910:cluster/clusterName';

const cluster = ecs.Cluster.fromClusterArn(this, 'Cluster', clusterArn);
python
cluster_arn = "arn:aws:ecs:us-east-1:012345678910:cluster/clusterName"

cluster = ecs.Cluster.from_cluster_arn(self, "Cluster", cluster_arn)
java
String clusterArn = "arn:aws:ecs:us-east-1:012345678910:cluster/clusterName";

ICluster cluster = Cluster.fromClusterArn(this, "Cluster", clusterArn);
csharp
var clusterArn = "arn:aws:ecs:us-east-1:012345678910:cluster/clusterName";

var cluster = Cluster.FromClusterArn(this, "Cluster", clusterArn);
go
clusterArn := "arn:aws:ecs:us-east-1:012345678910:cluster/clusterName"

cluster := ecs.Cluster_FromClusterArn(this, jsii.String("Cluster"), clusterArn)

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

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

ts
declare const vpc: ec2.Vpc;

const cluster = new ecs.Cluster(this, 'Cluster', {
  vpc,
});

// Either add default capacity
cluster.addCapacity('DefaultAutoScalingGroupCapacity', {
  instanceType: new ec2.InstanceType("t2.xlarge"),
});

// Or add customized capacity. Be sure to start the Amazon ECS-optimized AMI.
const autoScalingGroup = new autoscaling.AutoScalingGroup(this, 'ASG', {
  vpc,
  instanceType: new ec2.InstanceType('t2.xlarge'),
  machineImage: ecs.EcsOptimizedImage.amazonLinux(),
  // Or use Amazon ECS-Optimized Amazon Linux 2 AMI
  // machineImage: EcsOptimizedImage.amazonLinux2(),
  desiredCapacity: 3,
  // ... other options here ...
});

const capacityProvider = new ecs.AsgCapacityProvider(this, 'AsgCapacityProvider', {
  autoScalingGroup,
});
cluster.addAsgCapacityProvider(capacityProvider);
python
# vpc: ec2.Vpc


cluster = ecs.Cluster(self, "Cluster",
    vpc=vpc
)

# Either add default capacity
cluster.add_capacity("DefaultAutoScalingGroupCapacity",
    instance_type=ec2.InstanceType("t2.xlarge")
)

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

capacity_provider = ecs.AsgCapacityProvider(self, "AsgCapacityProvider",
    auto_scaling_group=auto_scaling_group
)
cluster.add_asg_capacity_provider(capacity_provider)
java
Vpc vpc;


Cluster cluster = Cluster.Builder.create(this, "Cluster")
        .vpc(vpc)
        .build();

// Either add default capacity
cluster.addCapacity("DefaultAutoScalingGroupCapacity", AddCapacityOptions.builder()
        .instanceType(new InstanceType("t2.xlarge"))
        .build());

// Or add customized capacity. Be sure to start the Amazon ECS-optimized AMI.
AutoScalingGroup autoScalingGroup = AutoScalingGroup.Builder.create(this, "ASG")
        .vpc(vpc)
        .instanceType(new InstanceType("t2.xlarge"))
        .machineImage(EcsOptimizedImage.amazonLinux())
        // Or use Amazon ECS-Optimized Amazon Linux 2 AMI
        // machineImage: EcsOptimizedImage.amazonLinux2(),
        .desiredCapacity(3)
        .build();

AsgCapacityProvider capacityProvider = AsgCapacityProvider.Builder.create(this, "AsgCapacityProvider")
        .autoScalingGroup(autoScalingGroup)
        .build();
cluster.addAsgCapacityProvider(capacityProvider);
csharp
Vpc vpc;


var cluster = new Cluster(this, "Cluster", new ClusterProps {
    Vpc = vpc
});

// Either add default capacity
cluster.AddCapacity("DefaultAutoScalingGroupCapacity", new AddCapacityOptions {
    InstanceType = new InstanceType("t2.xlarge")
});

// Or add customized capacity. Be sure to start the Amazon ECS-optimized AMI.
var autoScalingGroup = new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
    Vpc = vpc,
    InstanceType = new InstanceType("t2.xlarge"),
    MachineImage = EcsOptimizedImage.AmazonLinux(),
    // Or use Amazon ECS-Optimized Amazon Linux 2 AMI
    // machineImage: EcsOptimizedImage.amazonLinux2(),
    DesiredCapacity = 3
});

var capacityProvider = new AsgCapacityProvider(this, "AsgCapacityProvider", new AsgCapacityProviderProps {
    AutoScalingGroup = autoScalingGroup
});
cluster.AddAsgCapacityProvider(capacityProvider);
go
var vpc Vpc


cluster := ecs.NewCluster(this, jsii.String("Cluster"), &ClusterProps{
	Vpc: Vpc,
})

// Either add default capacity
cluster.AddCapacity(jsii.String("DefaultAutoScalingGroupCapacity"), &AddCapacityOptions{
	InstanceType: ec2.NewInstanceType(jsii.String("t2.xlarge")),
})

// Or add customized capacity. Be sure to start the Amazon ECS-optimized AMI.
autoScalingGroup := autoscaling.NewAutoScalingGroup(this, jsii.String("ASG"), &AutoScalingGroupProps{
	Vpc: Vpc,
	InstanceType: ec2.NewInstanceType(jsii.String("t2.xlarge")),
	MachineImage: ecs.EcsOptimizedImage_AmazonLinux(),
	// Or use Amazon ECS-Optimized Amazon Linux 2 AMI
	// machineImage: EcsOptimizedImage.amazonLinux2(),
	DesiredCapacity: jsii.Number(3),
})

capacityProvider := ecs.NewAsgCapacityProvider(this, jsii.String("AsgCapacityProvider"), &AsgCapacityProviderProps{
	AutoScalingGroup: AutoScalingGroup,
})
cluster.AddAsgCapacityProvider(capacityProvider)

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

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

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

ts
declare const vpc: ec2.Vpc;
const autoScalingGroup = new autoscaling.AutoScalingGroup(this, 'ASG', {
  machineImage: ecs.EcsOptimizedImage.amazonLinux({ cachedInContext: true }),
  vpc,
  instanceType: new ec2.InstanceType('t2.micro'),
});
python
# vpc: ec2.Vpc

auto_scaling_group = autoscaling.AutoScalingGroup(self, "ASG",
    machine_image=ecs.EcsOptimizedImage.amazon_linux(cached_in_context=True),
    vpc=vpc,
    instance_type=ec2.InstanceType("t2.micro")
)
java
Vpc vpc;

AutoScalingGroup autoScalingGroup = AutoScalingGroup.Builder.create(this, "ASG")
        .machineImage(EcsOptimizedImage.amazonLinux(EcsOptimizedImageOptions.builder().cachedInContext(true).build()))
        .vpc(vpc)
        .instanceType(new InstanceType("t2.micro"))
        .build();
csharp
Vpc vpc;

var autoScalingGroup = new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
    MachineImage = EcsOptimizedImage.AmazonLinux(new EcsOptimizedImageOptions { CachedInContext = true }),
    Vpc = vpc,
    InstanceType = new InstanceType("t2.micro")
});
go
var vpc Vpc

autoScalingGroup := autoscaling.NewAutoScalingGroup(this, jsii.String("ASG"), &AutoScalingGroupProps{
	MachineImage: ecs.EcsOptimizedImage_AmazonLinux(&EcsOptimizedImageOptions{
		CachedInContext: jsii.Boolean(true),
	}),
	Vpc: Vpc,
	InstanceType: ec2.NewInstanceType(jsii.String("t2.micro")),
})

To customize the cache key, use the additionalCacheKey parameter. This allows you to have multiple lookups with the same parameters cache their values separately. This can be useful if you want to scope the context variable to a construct (ie, using additionalCacheKey: this.node.path), so that if the value in the cache needs to be updated, it does not need to be updated for all constructs at the same time.

ts
declare const vpc: ec2.Vpc;
const autoScalingGroup = new autoscaling.AutoScalingGroup(this, 'ASG', {
  machineImage: ecs.EcsOptimizedImage.amazonLinux({ cachedInContext: true, additionalCacheKey: this.node.path }),
  vpc,
  instanceType: new ec2.InstanceType('t2.micro'),
});
python
# vpc: ec2.Vpc

auto_scaling_group = autoscaling.AutoScalingGroup(self, "ASG",
    machine_image=ecs.EcsOptimizedImage.amazon_linux(cached_in_context=True, additional_cache_key=self.node.path),
    vpc=vpc,
    instance_type=ec2.InstanceType("t2.micro")
)
java
Vpc vpc;

AutoScalingGroup autoScalingGroup = AutoScalingGroup.Builder.create(this, "ASG")
        .machineImage(EcsOptimizedImage.amazonLinux(EcsOptimizedImageOptions.builder().cachedInContext(true).additionalCacheKey(this.node.getPath()).build()))
        .vpc(vpc)
        .instanceType(new InstanceType("t2.micro"))
        .build();
csharp
Vpc vpc;

var autoScalingGroup = new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
    MachineImage = EcsOptimizedImage.AmazonLinux(new EcsOptimizedImageOptions { CachedInContext = true, AdditionalCacheKey = Node.Path }),
    Vpc = vpc,
    InstanceType = new InstanceType("t2.micro")
});
go
var vpc Vpc

autoScalingGroup := autoscaling.NewAutoScalingGroup(this, jsii.String("ASG"), &AutoScalingGroupProps{
	MachineImage: ecs.EcsOptimizedImage_AmazonLinux(&EcsOptimizedImageOptions{
		CachedInContext: jsii.Boolean(true),
		AdditionalCacheKey: this.Node.Path,
	}),
	Vpc: Vpc,
	InstanceType: ec2.NewInstanceType(jsii.String("t2.micro")),
})

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

ts
declare const vpc: ec2.Vpc;
const launchTemplate = new ec2.LaunchTemplate(this, 'ASG-LaunchTemplate', {
  instanceType: new ec2.InstanceType('t3.medium'),
  machineImage: ecs.EcsOptimizedImage.amazonLinux2(),
  userData: ec2.UserData.forLinux(),
});

const autoScalingGroup = new autoscaling.AutoScalingGroup(this, 'ASG', {
  vpc,
  mixedInstancesPolicy: {
    instancesDistribution: {
      onDemandPercentageAboveBaseCapacity: 50,
    },
    launchTemplate: launchTemplate,
  },
});

const cluster = new ecs.Cluster(this, 'Cluster', { vpc });

const capacityProvider = new ecs.AsgCapacityProvider(this, 'AsgCapacityProvider', {
  autoScalingGroup,
  machineImageType: ecs.MachineImageType.AMAZON_LINUX_2,
});

cluster.addAsgCapacityProvider(capacityProvider);
python
# vpc: ec2.Vpc

launch_template = ec2.LaunchTemplate(self, "ASG-LaunchTemplate",
    instance_type=ec2.InstanceType("t3.medium"),
    machine_image=ecs.EcsOptimizedImage.amazon_linux2(),
    user_data=ec2.UserData.for_linux()
)

auto_scaling_group = autoscaling.AutoScalingGroup(self, "ASG",
    vpc=vpc,
    mixed_instances_policy=autoscaling.MixedInstancesPolicy(
        instances_distribution=autoscaling.InstancesDistribution(
            on_demand_percentage_above_base_capacity=50
        ),
        launch_template=launch_template
    )
)

cluster = ecs.Cluster(self, "Cluster", vpc=vpc)

capacity_provider = ecs.AsgCapacityProvider(self, "AsgCapacityProvider",
    auto_scaling_group=auto_scaling_group,
    machine_image_type=ecs.MachineImageType.AMAZON_LINUX_2
)

cluster.add_asg_capacity_provider(capacity_provider)
java
Vpc vpc;

LaunchTemplate launchTemplate = LaunchTemplate.Builder.create(this, "ASG-LaunchTemplate")
        .instanceType(new InstanceType("t3.medium"))
        .machineImage(EcsOptimizedImage.amazonLinux2())
        .userData(UserData.forLinux())
        .build();

AutoScalingGroup autoScalingGroup = AutoScalingGroup.Builder.create(this, "ASG")
        .vpc(vpc)
        .mixedInstancesPolicy(MixedInstancesPolicy.builder()
                .instancesDistribution(InstancesDistribution.builder()
                        .onDemandPercentageAboveBaseCapacity(50)
                        .build())
                .launchTemplate(launchTemplate)
                .build())
        .build();

Cluster cluster = Cluster.Builder.create(this, "Cluster").vpc(vpc).build();

AsgCapacityProvider capacityProvider = AsgCapacityProvider.Builder.create(this, "AsgCapacityProvider")
        .autoScalingGroup(autoScalingGroup)
        .machineImageType(MachineImageType.AMAZON_LINUX_2)
        .build();

cluster.addAsgCapacityProvider(capacityProvider);
csharp
Vpc vpc;

var launchTemplate = new LaunchTemplate(this, "ASG-LaunchTemplate", new LaunchTemplateProps {
    InstanceType = new InstanceType("t3.medium"),
    MachineImage = EcsOptimizedImage.AmazonLinux2(),
    UserData = UserData.ForLinux()
});

var autoScalingGroup = new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
    Vpc = vpc,
    MixedInstancesPolicy = new MixedInstancesPolicy {
        InstancesDistribution = new InstancesDistribution {
            OnDemandPercentageAboveBaseCapacity = 50
        },
        LaunchTemplate = launchTemplate
    }
});

var cluster = new Cluster(this, "Cluster", new ClusterProps { Vpc = vpc });

var capacityProvider = new AsgCapacityProvider(this, "AsgCapacityProvider", new AsgCapacityProviderProps {
    AutoScalingGroup = autoScalingGroup,
    MachineImageType = MachineImageType.AMAZON_LINUX_2
});

cluster.AddAsgCapacityProvider(capacityProvider);
go
var vpc Vpc

launchTemplate := ec2.NewLaunchTemplate(this, jsii.String("ASG-LaunchTemplate"), &LaunchTemplateProps{
	InstanceType: ec2.NewInstanceType(jsii.String("t3.medium")),
	MachineImage: ecs.EcsOptimizedImage_AmazonLinux2(),
	UserData: ec2.UserData_ForLinux(),
})

autoScalingGroup := autoscaling.NewAutoScalingGroup(this, jsii.String("ASG"), &AutoScalingGroupProps{
	Vpc: Vpc,
	MixedInstancesPolicy: &MixedInstancesPolicy{
		InstancesDistribution: &InstancesDistribution{
			OnDemandPercentageAboveBaseCapacity: jsii.Number(50),
		},
		LaunchTemplate: launchTemplate,
	},
})

cluster := ecs.NewCluster(this, jsii.String("Cluster"), &ClusterProps{
	Vpc: Vpc,
})

capacityProvider := ecs.NewAsgCapacityProvider(this, jsii.String("AsgCapacityProvider"), &AsgCapacityProviderProps{
	AutoScalingGroup: AutoScalingGroup,
	MachineImageType: ecs.MachineImageType_AMAZON_LINUX_2,
})

cluster.AddAsgCapacityProvider(capacityProvider)

The following code retrieve the Amazon Resource Names (ARNs) of tasks that are a part of a specified ECS cluster. It's useful when you want to grant permissions to a task to access other AWS resources.

ts
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;
const taskARNs = cluster.arnForTasks('*'); // arn:aws:ecs:<region>:<regionId>:task/<clusterName>/*

// Grant the task permission to access other AWS resources
taskDefinition.addToTaskRolePolicy(
  new iam.PolicyStatement({
    actions: ['ecs:UpdateTaskProtection'],
    resources: [taskARNs],
  })
)
python
# cluster: ecs.Cluster
# task_definition: 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(
    iam.PolicyStatement(
        actions=["ecs:UpdateTaskProtection"],
        resources=[task_ar_ns]
    ))
java
Cluster cluster;
TaskDefinition taskDefinition;

String taskARNs = cluster.arnForTasks("*"); // arn:aws:ecs:<region>:<regionId>:task/<clusterName>/*

// Grant the task permission to access other AWS resources
taskDefinition.addToTaskRolePolicy(
PolicyStatement.Builder.create()
        .actions(List.of("ecs:UpdateTaskProtection"))
        .resources(List.of(taskARNs))
        .build());
csharp
Cluster cluster;
TaskDefinition taskDefinition;

var taskARNs = cluster.ArnForTasks("*"); // arn:aws:ecs:<region>:<regionId>:task/<clusterName>/*

// Grant the task permission to access other AWS resources
taskDefinition.AddToTaskRolePolicy(
new PolicyStatement(new PolicyStatementProps {
    Actions = new [] { "ecs:UpdateTaskProtection" },
    Resources = new [] { taskARNs }
}));
go
var cluster Cluster
var taskDefinition TaskDefinition

taskARNs := cluster.ArnForTasks(jsii.String("*")) // arn:aws:ecs:<region>:<regionId>:task/<clusterName>/*

// Grant the task permission to access other AWS resources
taskDefinition.AddToTaskRolePolicy(
iam.NewPolicyStatement(&PolicyStatementProps{
	Actions: []*string{
		jsii.String("ecs:UpdateTaskProtection"),
	},
	Resources: []*string{
		taskARNs,
	},
}))

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

ts
// Assume 'cluster' is an instance of ecs.Cluster
declare const cluster: ecs.Cluster;
declare const taskRole: iam.Role;

// Grant ECS Task Protection permissions to the role
// Now 'taskRole' has the 'ecs:UpdateTaskProtection' permission on all tasks in the cluster
cluster.grantTaskProtection(taskRole);
python
# Assume 'cluster' is an instance of ecs.Cluster
# cluster: ecs.Cluster
# task_role: 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)
java
// Assume 'cluster' is an instance of ecs.Cluster
Cluster cluster;
Role taskRole;


// Grant ECS Task Protection permissions to the role
// Now 'taskRole' has the 'ecs:UpdateTaskProtection' permission on all tasks in the cluster
cluster.grantTaskProtection(taskRole);
csharp
// Assume 'cluster' is an instance of ecs.Cluster
Cluster cluster;
Role taskRole;


// Grant ECS Task Protection permissions to the role
// Now 'taskRole' has the 'ecs:UpdateTaskProtection' permission on all tasks in the cluster
cluster.GrantTaskProtection(taskRole);
go
// Assume 'cluster' is an instance of ecs.Cluster
var cluster Cluster
var taskRole Role


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

Bottlerocket ​

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

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

The following example adds Bottlerocket capacity to the cluster:

ts
declare const cluster: ecs.Cluster;

cluster.addCapacity('bottlerocket-asg', {
  minCapacity: 2,
  instanceType: new ec2.InstanceType('c5.large'),
  machineImage: new ecs.BottleRocketImage(),
});
python
# cluster: ecs.Cluster


cluster.add_capacity("bottlerocket-asg",
    min_capacity=2,
    instance_type=ec2.InstanceType("c5.large"),
    machine_image=ecs.BottleRocketImage()
)
java
Cluster cluster;


cluster.addCapacity("bottlerocket-asg", AddCapacityOptions.builder()
        .minCapacity(2)
        .instanceType(new InstanceType("c5.large"))
        .machineImage(new BottleRocketImage())
        .build());
csharp
Cluster cluster;


cluster.AddCapacity("bottlerocket-asg", new AddCapacityOptions {
    MinCapacity = 2,
    InstanceType = new InstanceType("c5.large"),
    MachineImage = new BottleRocketImage()
});
go
var cluster Cluster


cluster.AddCapacity(jsii.String("bottlerocket-asg"), &AddCapacityOptions{
	MinCapacity: jsii.Number(2),
	InstanceType: ec2.NewInstanceType(jsii.String("c5.large")),
	MachineImage: ecs.NewBottleRocketImage(),
})

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

ts
declare const cluster: ecs.Cluster;

cluster.addCapacity('bottlerocket-asg', {
  instanceType: new ec2.InstanceType('p3.2xlarge'),
  machineImage: new ecs.BottleRocketImage({
      variant: ecs.BottlerocketEcsVariant.AWS_ECS_2_NVIDIA,
  }),
});
python
# cluster: ecs.Cluster


cluster.add_capacity("bottlerocket-asg",
    instance_type=ec2.InstanceType("p3.2xlarge"),
    machine_image=ecs.BottleRocketImage(
        variant=ecs.BottlerocketEcsVariant.AWS_ECS_2_NVIDIA
    )
)
java
Cluster cluster;


cluster.addCapacity("bottlerocket-asg", AddCapacityOptions.builder()
        .instanceType(new InstanceType("p3.2xlarge"))
        .machineImage(BottleRocketImage.Builder.create()
                .variant(BottlerocketEcsVariant.AWS_ECS_2_NVIDIA)
                .build())
        .build());
csharp
Cluster cluster;


cluster.AddCapacity("bottlerocket-asg", new AddCapacityOptions {
    InstanceType = new InstanceType("p3.2xlarge"),
    MachineImage = new BottleRocketImage(new BottleRocketImageProps {
        Variant = BottlerocketEcsVariant.AWS_ECS_2_NVIDIA
    })
});
go
var cluster Cluster


cluster.AddCapacity(jsii.String("bottlerocket-asg"), &AddCapacityOptions{
	InstanceType: ec2.NewInstanceType(jsii.String("p3.2xlarge")),
	MachineImage: ecs.NewBottleRocketImage(&BottleRocketImageProps{
		Variant: 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.

ts
declare const cluster: ecs.Cluster;

cluster.addCapacity('graviton-cluster', {
  minCapacity: 2,
  instanceType: new ec2.InstanceType('c6g.large'),
  machineImage: ecs.EcsOptimizedImage.amazonLinux2(ecs.AmiHardwareType.ARM),
});
python
# cluster: ecs.Cluster


cluster.add_capacity("graviton-cluster",
    min_capacity=2,
    instance_type=ec2.InstanceType("c6g.large"),
    machine_image=ecs.EcsOptimizedImage.amazon_linux2(ecs.AmiHardwareType.ARM)
)
java
Cluster cluster;


cluster.addCapacity("graviton-cluster", AddCapacityOptions.builder()
        .minCapacity(2)
        .instanceType(new InstanceType("c6g.large"))
        .machineImage(EcsOptimizedImage.amazonLinux2(AmiHardwareType.ARM))
        .build());
csharp
Cluster cluster;


cluster.AddCapacity("graviton-cluster", new AddCapacityOptions {
    MinCapacity = 2,
    InstanceType = new InstanceType("c6g.large"),
    MachineImage = EcsOptimizedImage.AmazonLinux2(AmiHardwareType.ARM)
});
go
var cluster Cluster


cluster.AddCapacity(jsii.String("graviton-cluster"), &AddCapacityOptions{
	MinCapacity: jsii.Number(2),
	InstanceType: ec2.NewInstanceType(jsii.String("c6g.large")),
	MachineImage: ecs.EcsOptimizedImage_AmazonLinux2(ecs.AmiHardwareType_ARM),
})

Bottlerocket is also supported:

ts
declare const cluster: ecs.Cluster;

cluster.addCapacity('graviton-cluster', {
  minCapacity: 2,
  instanceType: new ec2.InstanceType('c6g.large'),
  machineImageType: ecs.MachineImageType.BOTTLEROCKET,
});
python
# cluster: ecs.Cluster


cluster.add_capacity("graviton-cluster",
    min_capacity=2,
    instance_type=ec2.InstanceType("c6g.large"),
    machine_image_type=ecs.MachineImageType.BOTTLEROCKET
)
java
Cluster cluster;


cluster.addCapacity("graviton-cluster", AddCapacityOptions.builder()
        .minCapacity(2)
        .instanceType(new InstanceType("c6g.large"))
        .machineImageType(MachineImageType.BOTTLEROCKET)
        .build());
csharp
Cluster cluster;


cluster.AddCapacity("graviton-cluster", new AddCapacityOptions {
    MinCapacity = 2,
    InstanceType = new InstanceType("c6g.large"),
    MachineImageType = MachineImageType.BOTTLEROCKET
});
go
var cluster Cluster


cluster.AddCapacity(jsii.String("graviton-cluster"), &AddCapacityOptions{
	MinCapacity: jsii.Number(2),
	InstanceType: ec2.NewInstanceType(jsii.String("c6g.large")),
	MachineImageType: ecs.MachineImageType_BOTTLEROCKET,
})

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.

ts
declare const cluster: ecs.Cluster;

cluster.addCapacity('neuron-cluster', {
  minCapacity: 2,
  instanceType: new ec2.InstanceType('inf1.xlarge'),
  machineImage: ecs.EcsOptimizedImage.amazonLinux2(ecs.AmiHardwareType.NEURON),
});
python
# cluster: ecs.Cluster


cluster.add_capacity("neuron-cluster",
    min_capacity=2,
    instance_type=ec2.InstanceType("inf1.xlarge"),
    machine_image=ecs.EcsOptimizedImage.amazon_linux2(ecs.AmiHardwareType.NEURON)
)
java
Cluster cluster;


cluster.addCapacity("neuron-cluster", AddCapacityOptions.builder()
        .minCapacity(2)
        .instanceType(new InstanceType("inf1.xlarge"))
        .machineImage(EcsOptimizedImage.amazonLinux2(AmiHardwareType.NEURON))
        .build());
csharp
Cluster cluster;


cluster.AddCapacity("neuron-cluster", new AddCapacityOptions {
    MinCapacity = 2,
    InstanceType = new InstanceType("inf1.xlarge"),
    MachineImage = EcsOptimizedImage.AmazonLinux2(AmiHardwareType.NEURON)
});
go
var cluster Cluster


cluster.AddCapacity(jsii.String("neuron-cluster"), &AddCapacityOptions{
	MinCapacity: jsii.Number(2),
	InstanceType: ec2.NewInstanceType(jsii.String("inf1.xlarge")),
	MachineImage: ecs.EcsOptimizedImage_AmazonLinux2(ecs.AmiHardwareType_NEURON),
})

Spot Instances ​

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

ts
declare const cluster: ecs.Cluster;

// Add an AutoScalingGroup with spot instances to the existing cluster
cluster.addCapacity('AsgSpot', {
  maxCapacity: 2,
  minCapacity: 2,
  desiredCapacity: 2,
  instanceType: new ec2.InstanceType('c5.xlarge'),
  spotPrice: '0.0735',
  // Enable the Automated Spot Draining support for Amazon ECS
  spotInstanceDraining: true,
});
python
# cluster: 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=ec2.InstanceType("c5.xlarge"),
    spot_price="0.0735",
    # Enable the Automated Spot Draining support for Amazon ECS
    spot_instance_draining=True
)
java
Cluster cluster;


// Add an AutoScalingGroup with spot instances to the existing cluster
cluster.addCapacity("AsgSpot", AddCapacityOptions.builder()
        .maxCapacity(2)
        .minCapacity(2)
        .desiredCapacity(2)
        .instanceType(new InstanceType("c5.xlarge"))
        .spotPrice("0.0735")
        // Enable the Automated Spot Draining support for Amazon ECS
        .spotInstanceDraining(true)
        .build());
csharp
Cluster cluster;


// Add an AutoScalingGroup with spot instances to the existing cluster
cluster.AddCapacity("AsgSpot", new AddCapacityOptions {
    MaxCapacity = 2,
    MinCapacity = 2,
    DesiredCapacity = 2,
    InstanceType = new InstanceType("c5.xlarge"),
    SpotPrice = "0.0735",
    // Enable the Automated Spot Draining support for Amazon ECS
    SpotInstanceDraining = true
});
go
var cluster Cluster


// Add an AutoScalingGroup with spot instances to the existing cluster
cluster.AddCapacity(jsii.String("AsgSpot"), &AddCapacityOptions{
	MaxCapacity: jsii.Number(2),
	MinCapacity: jsii.Number(2),
	DesiredCapacity: jsii.Number(2),
	InstanceType: ec2.NewInstanceType(jsii.String("c5.xlarge")),
	SpotPrice: jsii.String("0.0735"),
	// Enable the Automated Spot Draining support for Amazon ECS
	SpotInstanceDraining: jsii.Boolean(true),
})

SNS Topic Encryption ​

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

ts
// Given
declare const cluster: ecs.Cluster;
declare const key: kms.Key;
// Then, use that key to encrypt the lifecycle-event SNS Topic.
cluster.addCapacity('ASGEncryptedSNS', {
  instanceType: new ec2.InstanceType("t2.xlarge"),
  desiredCapacity: 3,
  topicEncryptionKey: key,
});
python
# Given
# cluster: ecs.Cluster
# key: kms.Key

# Then, use that key to encrypt the lifecycle-event SNS Topic.
cluster.add_capacity("ASGEncryptedSNS",
    instance_type=ec2.InstanceType("t2.xlarge"),
    desired_capacity=3,
    topic_encryption_key=key
)
java
// Given
Cluster cluster;
Key key;

// Then, use that key to encrypt the lifecycle-event SNS Topic.
cluster.addCapacity("ASGEncryptedSNS", AddCapacityOptions.builder()
        .instanceType(new InstanceType("t2.xlarge"))
        .desiredCapacity(3)
        .topicEncryptionKey(key)
        .build());
csharp
// Given
Cluster cluster;
Key key;

// Then, use that key to encrypt the lifecycle-event SNS Topic.
cluster.AddCapacity("ASGEncryptedSNS", new AddCapacityOptions {
    InstanceType = new InstanceType("t2.xlarge"),
    DesiredCapacity = 3,
    TopicEncryptionKey = key
});
go
// Given
var cluster Cluster
var key Key

// Then, use that key to encrypt the lifecycle-event SNS Topic.
cluster.AddCapacity(jsii.String("ASGEncryptedSNS"), &AddCapacityOptions{
	InstanceType: ec2.NewInstanceType(jsii.String("t2.xlarge")),
	DesiredCapacity: jsii.Number(3),
	TopicEncryptionKey: key,
})

Container Insights ​

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

ts
const cluster = new ecs.Cluster(this, 'Cluster', {
  containerInsightsV2: ecs.ContainerInsights.ENHANCED
});
python
cluster = ecs.Cluster(self, "Cluster",
    container_insights_v2=ecs.ContainerInsights.ENHANCED
)
java
Cluster cluster = Cluster.Builder.create(this, "Cluster")
        .containerInsightsV2(ContainerInsights.ENHANCED)
        .build();
csharp
var cluster = new Cluster(this, "Cluster", new ClusterProps {
    ContainerInsightsV2 = ContainerInsights.ENHANCED
});
go
cluster := ecs.NewCluster(this, jsii.String("Cluster"), &ClusterProps{
	ContainerInsightsV2: 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 (memoryLimitMiB and cpu):

ts
const fargateTaskDefinition = new ecs.FargateTaskDefinition(this, 'TaskDef', {
  memoryLimitMiB: 512,
  cpu: 256,
});
python
fargate_task_definition = ecs.FargateTaskDefinition(self, "TaskDef",
    memory_limit_mi_b=512,
    cpu=256
)
java
FargateTaskDefinition fargateTaskDefinition = FargateTaskDefinition.Builder.create(this, "TaskDef")
        .memoryLimitMiB(512)
        .cpu(256)
        .build();
csharp
var fargateTaskDefinition = new FargateTaskDefinition(this, "TaskDef", new FargateTaskDefinitionProps {
    MemoryLimitMiB = 512,
    Cpu = 256
});
go
fargateTaskDefinition := ecs.NewFargateTaskDefinition(this, jsii.String("TaskDef"), &FargateTaskDefinitionProps{
	MemoryLimitMiB: jsii.Number(512),
	Cpu: jsii.Number(256),
})

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

ts
const fargateTaskDefinition = new ecs.FargateTaskDefinition(this, 'TaskDef', {
  memoryLimitMiB: 512,
  cpu: 256,
  ephemeralStorageGiB: 100,
});
python
fargate_task_definition = ecs.FargateTaskDefinition(self, "TaskDef",
    memory_limit_mi_b=512,
    cpu=256,
    ephemeral_storage_gi_b=100
)
java
FargateTaskDefinition fargateTaskDefinition = FargateTaskDefinition.Builder.create(this, "TaskDef")
        .memoryLimitMiB(512)
        .cpu(256)
        .ephemeralStorageGiB(100)
        .build();
csharp
var fargateTaskDefinition = new FargateTaskDefinition(this, "TaskDef", new FargateTaskDefinitionProps {
    MemoryLimitMiB = 512,
    Cpu = 256,
    EphemeralStorageGiB = 100
});
go
fargateTaskDefinition := ecs.NewFargateTaskDefinition(this, jsii.String("TaskDef"), &FargateTaskDefinitionProps{
	MemoryLimitMiB: jsii.Number(512),
	Cpu: jsii.Number(256),
	EphemeralStorageGiB: jsii.Number(100),
})

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

ts
const fargateTaskDefinition = new ecs.FargateTaskDefinition(this, 'TaskDef', {
  runtimePlatform: {
    operatingSystemFamily: ecs.OperatingSystemFamily.LINUX,
    cpuArchitecture: ecs.CpuArchitecture.ARM64,
  },
  memoryLimitMiB: 512,
  cpu: 256,
  pidMode: ecs.PidMode.TASK,
});
python
fargate_task_definition = ecs.FargateTaskDefinition(self, "TaskDef",
    runtime_platform=ecs.RuntimePlatform(
        operating_system_family=ecs.OperatingSystemFamily.LINUX,
        cpu_architecture=ecs.CpuArchitecture.ARM64
    ),
    memory_limit_mi_b=512,
    cpu=256,
    pid_mode=ecs.PidMode.TASK
)
java
FargateTaskDefinition fargateTaskDefinition = FargateTaskDefinition.Builder.create(this, "TaskDef")
        .runtimePlatform(RuntimePlatform.builder()
                .operatingSystemFamily(OperatingSystemFamily.LINUX)
                .cpuArchitecture(CpuArchitecture.ARM64)
                .build())
        .memoryLimitMiB(512)
        .cpu(256)
        .pidMode(PidMode.TASK)
        .build();
csharp
var fargateTaskDefinition = new FargateTaskDefinition(this, "TaskDef", new FargateTaskDefinitionProps {
    RuntimePlatform = new RuntimePlatform {
        OperatingSystemFamily = OperatingSystemFamily.LINUX,
        CpuArchitecture = CpuArchitecture.ARM64
    },
    MemoryLimitMiB = 512,
    Cpu = 256,
    PidMode = PidMode.TASK
});
go
fargateTaskDefinition := ecs.NewFargateTaskDefinition(this, jsii.String("TaskDef"), &FargateTaskDefinitionProps{
	RuntimePlatform: &RuntimePlatform{
		OperatingSystemFamily: ecs.OperatingSystemFamily_LINUX(),
		CpuArchitecture: ecs.CpuArchitecture_ARM64(),
	},
	MemoryLimitMiB: jsii.Number(512),
	Cpu: jsii.Number(256),
	PidMode: ecs.PidMode_TASK,
})

Note: pidMode is only supported for tasks that are hosted on AWS Fargate if the tasks are using platform version 1.4.0 or later (Linux). Only the task option is supported for Linux containers. pidMode isn't supported for Windows containers on Fargate. If pidMode is specified for a Fargate task, then runtimePlatform.operatingSystemFamily must also be specified.

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

ts
const fargateTaskDefinition = new ecs.FargateTaskDefinition(this, 'TaskDef', {
  memoryLimitMiB: 512,
  cpu: 256,
});
const container = fargateTaskDefinition.addContainer("WebContainer", {
  // Use an image from DockerHub
  image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  // ... other options here ...
});
python
fargate_task_definition = ecs.FargateTaskDefinition(self, "TaskDef",
    memory_limit_mi_b=512,
    cpu=256
)
container = fargate_task_definition.add_container("WebContainer",
    # Use an image from DockerHub
    image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")
)
java
FargateTaskDefinition fargateTaskDefinition = FargateTaskDefinition.Builder.create(this, "TaskDef")
        .memoryLimitMiB(512)
        .cpu(256)
        .build();
ContainerDefinition container = fargateTaskDefinition.addContainer("WebContainer", ContainerDefinitionOptions.builder()
        // Use an image from DockerHub
        .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
        .build());
csharp
var fargateTaskDefinition = new FargateTaskDefinition(this, "TaskDef", new FargateTaskDefinitionProps {
    MemoryLimitMiB = 512,
    Cpu = 256
});
var container = fargateTaskDefinition.AddContainer("WebContainer", new ContainerDefinitionOptions {
    // Use an image from DockerHub
    Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
});
go
fargateTaskDefinition := ecs.NewFargateTaskDefinition(this, jsii.String("TaskDef"), &FargateTaskDefinitionProps{
	MemoryLimitMiB: jsii.Number(512),
	Cpu: jsii.Number(256),
})
container := fargateTaskDefinition.AddContainer(jsii.String("WebContainer"), &ContainerDefinitionOptions{
	// Use an image from DockerHub
	Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
})

For an Ec2TaskDefinition:

ts
const ec2TaskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef', {
  networkMode: ecs.NetworkMode.BRIDGE,
});

const container = ec2TaskDefinition.addContainer("WebContainer", {
  // Use an image from DockerHub
  image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  memoryLimitMiB: 1024,
  // ... other options here ...
});
python
ec2_task_definition = ecs.Ec2TaskDefinition(self, "TaskDef",
    network_mode=ecs.NetworkMode.BRIDGE
)

container = ec2_task_definition.add_container("WebContainer",
    # Use an image from DockerHub
    image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample"),
    memory_limit_mi_b=1024
)
java
Ec2TaskDefinition ec2TaskDefinition = Ec2TaskDefinition.Builder.create(this, "TaskDef")
        .networkMode(NetworkMode.BRIDGE)
        .build();

ContainerDefinition container = ec2TaskDefinition.addContainer("WebContainer", ContainerDefinitionOptions.builder()
        // Use an image from DockerHub
        .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
        .memoryLimitMiB(1024)
        .build());
csharp
var ec2TaskDefinition = new Ec2TaskDefinition(this, "TaskDef", new Ec2TaskDefinitionProps {
    NetworkMode = NetworkMode.BRIDGE
});

var container = ec2TaskDefinition.AddContainer("WebContainer", new ContainerDefinitionOptions {
    // Use an image from DockerHub
    Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
    MemoryLimitMiB = 1024
});
go
ec2TaskDefinition := ecs.NewEc2TaskDefinition(this, jsii.String("TaskDef"), &Ec2TaskDefinitionProps{
	NetworkMode: ecs.NetworkMode_BRIDGE,
})

container := ec2TaskDefinition.AddContainer(jsii.String("WebContainer"), &ContainerDefinitionOptions{
	// Use an image from DockerHub
	Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	MemoryLimitMiB: jsii.Number(1024),
})

For an ExternalTaskDefinition:

ts
const externalTaskDefinition = new ecs.ExternalTaskDefinition(this, 'TaskDef');

const container = externalTaskDefinition.addContainer("WebContainer", {
  // Use an image from DockerHub
  image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  memoryLimitMiB: 1024,
  // ... other options here ...
});
python
external_task_definition = ecs.ExternalTaskDefinition(self, "TaskDef")

container = external_task_definition.add_container("WebContainer",
    # Use an image from DockerHub
    image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample"),
    memory_limit_mi_b=1024
)
java
ExternalTaskDefinition externalTaskDefinition = new ExternalTaskDefinition(this, "TaskDef");

ContainerDefinition container = externalTaskDefinition.addContainer("WebContainer", ContainerDefinitionOptions.builder()
        // Use an image from DockerHub
        .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
        .memoryLimitMiB(1024)
        .build());
csharp
var externalTaskDefinition = new ExternalTaskDefinition(this, "TaskDef");

var container = externalTaskDefinition.AddContainer("WebContainer", new ContainerDefinitionOptions {
    // Use an image from DockerHub
    Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
    MemoryLimitMiB = 1024
});
go
externalTaskDefinition := ecs.NewExternalTaskDefinition(this, jsii.String("TaskDef"))

container := externalTaskDefinition.AddContainer(jsii.String("WebContainer"), &ContainerDefinitionOptions{
	// Use an image from DockerHub
	Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	MemoryLimitMiB: jsii.Number(1024),
})

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

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

ts
declare const taskDefinition: ecs.TaskDefinition;

taskDefinition.addContainer("WebContainer", {
  image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  memoryLimitMiB: 1024,
  portMappings: [{ containerPort: 3000 }],
});
python
# task_definition: ecs.TaskDefinition


task_definition.add_container("WebContainer",
    image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample"),
    memory_limit_mi_b=1024,
    port_mappings=[ecs.PortMapping(container_port=3000)]
)
java
TaskDefinition taskDefinition;


taskDefinition.addContainer("WebContainer", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
        .memoryLimitMiB(1024)
        .portMappings(List.of(PortMapping.builder().containerPort(3000).build()))
        .build());
csharp
TaskDefinition taskDefinition;


taskDefinition.AddContainer("WebContainer", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
    MemoryLimitMiB = 1024,
    PortMappings = new [] { new PortMapping { ContainerPort = 3000 } }
});
go
var taskDefinition TaskDefinition


taskDefinition.AddContainer(jsii.String("WebContainer"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	MemoryLimitMiB: jsii.Number(1024),
	PortMappings: []PortMapping{
		&PortMapping{
			ContainerPort: jsii.Number(3000),
		},
	},
})

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

ts
declare const container: ecs.ContainerDefinition;

container.addPortMappings({
  containerPort: 3000,
});
python
# container: ecs.ContainerDefinition


container.add_port_mappings(
    container_port=3000
)
java
ContainerDefinition container;


container.addPortMappings(PortMapping.builder()
        .containerPort(3000)
        .build());
csharp
ContainerDefinition container;


container.AddPortMappings(new PortMapping {
    ContainerPort = 3000
});
go
var container ContainerDefinition


container.AddPortMappings(&PortMapping{
	ContainerPort: jsii.Number(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.

ts
declare const container: ecs.ContainerDefinition;

container.addPortMappings({
    containerPort: ecs.ContainerDefinition.CONTAINER_PORT_USE_RANGE,
    containerPortRange: '8080-8081',
});
python
# container: ecs.ContainerDefinition


container.add_port_mappings(
    container_port=ecs.ContainerDefinition.CONTAINER_PORT_USE_RANGE,
    container_port_range="8080-8081"
)
java
ContainerDefinition container;


container.addPortMappings(PortMapping.builder()
        .containerPort(ContainerDefinition.CONTAINER_PORT_USE_RANGE)
        .containerPortRange("8080-8081")
        .build());
csharp
ContainerDefinition container;


container.AddPortMappings(new PortMapping {
    ContainerPort = ContainerDefinition.CONTAINER_PORT_USE_RANGE,
    ContainerPortRange = "8080-8081"
});
go
var container ContainerDefinition


container.AddPortMappings(&PortMapping{
	ContainerPort: ecs.ContainerDefinition_CONTAINER_PORT_USE_RANGE(),
	ContainerPortRange: jsii.String("8080-8081"),
})

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

ts
const fargateTaskDefinition = new ecs.FargateTaskDefinition(this, 'TaskDef', {
  memoryLimitMiB: 512,
  cpu: 256,
});
const volume = {
  // Use an Elastic FileSystem
  name: "mydatavolume",
  efsVolumeConfiguration: {
    fileSystemId: "EFS",
    // ... other options here ...
  },
};

const container = fargateTaskDefinition.addVolume(volume);
python
fargate_task_definition = ecs.FargateTaskDefinition(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)
java
FargateTaskDefinition fargateTaskDefinition = FargateTaskDefinition.Builder.create(this, "TaskDef")
        .memoryLimitMiB(512)
        .cpu(256)
        .build();
Map<String, Object> volume = Map.of(
        // Use an Elastic FileSystem
        "name", "mydatavolume",
        "efsVolumeConfiguration", Map.of(
                "fileSystemId", "EFS"));

void container = fargateTaskDefinition.addVolume(volume);
csharp
var fargateTaskDefinition = new FargateTaskDefinition(this, "TaskDef", new FargateTaskDefinitionProps {
    MemoryLimitMiB = 512,
    Cpu = 256
});
IDictionary<string, object> volume = new Dictionary<string, object> {
    // Use an Elastic FileSystem
    { "name", "mydatavolume" },
    { "efsVolumeConfiguration", new Dictionary<string, string> {
        { "fileSystemId", "EFS" }
    } }
};

var container = fargateTaskDefinition.AddVolume(volume);
go
fargateTaskDefinition := ecs.NewFargateTaskDefinition(this, jsii.String("TaskDef"), &FargateTaskDefinitionProps{
	MemoryLimitMiB: jsii.Number(512),
	Cpu: jsii.Number(256),
})
volume := map[string]interface{}{
	// Use an Elastic FileSystem
	"name": jsii.String("mydatavolume"),
	"efsVolumeConfiguration": map[string]*string{
		"fileSystemId": jsii.String("EFS"),
	},
}

container := fargateTaskDefinition.AddVolume(volume)

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

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

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

ts
const taskDefinition = new ecs.TaskDefinition(this, 'TaskDef', {
  memoryMiB: '512',
  cpu: '256',
  networkMode: ecs.NetworkMode.AWS_VPC,
  compatibility: ecs.Compatibility.EC2_AND_FARGATE,
});
python
task_definition = ecs.TaskDefinition(self, "TaskDef",
    memory_mi_b="512",
    cpu="256",
    network_mode=ecs.NetworkMode.AWS_VPC,
    compatibility=ecs.Compatibility.EC2_AND_FARGATE
)
java
TaskDefinition taskDefinition = TaskDefinition.Builder.create(this, "TaskDef")
        .memoryMiB("512")
        .cpu("256")
        .networkMode(NetworkMode.AWS_VPC)
        .compatibility(Compatibility.EC2_AND_FARGATE)
        .build();
csharp
var taskDefinition = new TaskDefinition(this, "TaskDef", new TaskDefinitionProps {
    MemoryMiB = "512",
    Cpu = "256",
    NetworkMode = NetworkMode.AWS_VPC,
    Compatibility = Compatibility.EC2_AND_FARGATE
});
go
taskDefinition := ecs.NewTaskDefinition(this, jsii.String("TaskDef"), &TaskDefinitionProps{
	MemoryMiB: jsii.String("512"),
	Cpu: jsii.String("256"),
	NetworkMode: ecs.NetworkMode_AWS_VPC,
	Compatibility: ecs.Compatibility_EC2_AND_FARGATE,
})

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

ts
declare const role: iam.IGrantable;
const taskDef = new ecs.TaskDefinition(this, 'TaskDef', {
  cpu: '512',
  memoryMiB: '512',
  compatibility: ecs.Compatibility.EC2_AND_FARGATE,
});

// Gives role required permissions to run taskDef
taskDef.grantRun(role);
python
# role: iam.IGrantable

task_def = ecs.TaskDefinition(self, "TaskDef",
    cpu="512",
    memory_mi_b="512",
    compatibility=ecs.Compatibility.EC2_AND_FARGATE
)

# Gives role required permissions to run taskDef
task_def.grant_run(role)
java
IGrantable role;

TaskDefinition taskDef = TaskDefinition.Builder.create(this, "TaskDef")
        .cpu("512")
        .memoryMiB("512")
        .compatibility(Compatibility.EC2_AND_FARGATE)
        .build();

// Gives role required permissions to run taskDef
taskDef.grantRun(role);
csharp
IGrantable role;

var taskDef = new TaskDefinition(this, "TaskDef", new TaskDefinitionProps {
    Cpu = "512",
    MemoryMiB = "512",
    Compatibility = Compatibility.EC2_AND_FARGATE
});

// Gives role required permissions to run taskDef
taskDef.GrantRun(role);
go
var role IGrantable

taskDef := ecs.NewTaskDefinition(this, jsii.String("TaskDef"), &TaskDefinitionProps{
	Cpu: jsii.String("512"),
	MemoryMiB: jsii.String("512"),
	Compatibility: ecs.Compatibility_EC2_AND_FARGATE,
})

// Gives role required permissions to run taskDef
taskDef.GrantRun(role)

To deploy containerized applications that require the allocation of standard input (stdin) or a terminal (tty), use the interactive property.

This parameter corresponds to OpenStdin in the Create a container section of the Docker Remote API and the --interactive option to docker run.

ts
declare const taskDefinition: ecs.TaskDefinition;

taskDefinition.addContainer("Container", {
  image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  interactive: true,
});
python
# task_definition: ecs.TaskDefinition


task_definition.add_container("Container",
    image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample"),
    interactive=True
)
java
TaskDefinition taskDefinition;


taskDefinition.addContainer("Container", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
        .interactive(true)
        .build());
csharp
TaskDefinition taskDefinition;


taskDefinition.AddContainer("Container", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
    Interactive = true
});
go
var taskDefinition TaskDefinition


taskDefinition.AddContainer(jsii.String("Container"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	Interactive: jsii.Boolean(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.

  • ecs.ContainerImage.fromRegistry(imageName): use a public image.
  • ecs.ContainerImage.fromRegistry(imageName, { credentials: mySecret }): use a private image that requires credentials.
  • ecs.ContainerImage.fromEcrRepository(repo, tagOrDigest): use the given ECR repository as the image to start. If no tag or digest is provided, "latest" is assumed.
  • ecs.ContainerImage.fromAsset('./image'): build and upload an image directly from a Dockerfile in your source directory.
  • ecs.ContainerImage.fromDockerImageAsset(asset): uses an existing aws-cdk-lib/aws-ecr-assets.DockerImageAsset as a container image.
  • ecs.ContainerImage.fromTarball(file): use an existing tarball.
  • new ecs.TagParameterContainerImage(repository): use the given ECR repository as the image but a CloudFormation parameter as the tag.

Environment variables ​

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

ts
declare const secret: secretsmanager.Secret;
declare const dbSecret: secretsmanager.Secret;
declare const parameter: ssm.StringParameter;
declare const taskDefinition: ecs.TaskDefinition;
declare const s3Bucket: s3.Bucket;

const newContainer = taskDefinition.addContainer('container', {
  image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  memoryLimitMiB: 1024,
  environment: { // clear text, not for sensitive data
    STAGE: 'prod',
  },
  environmentFiles: [ // list of environment files hosted either on local disk or S3
    ecs.EnvironmentFile.fromAsset('./demo-env-file.env'),
    ecs.EnvironmentFile.fromBucket(s3Bucket, 'assets/demo-env-file.env'),
  ],
  secrets: { // Retrieved from AWS Secrets Manager or AWS Systems Manager Parameter Store at container start-up.
    SECRET: ecs.Secret.fromSecretsManager(secret),
    DB_PASSWORD: ecs.Secret.fromSecretsManager(dbSecret, 'password'), // Reference a specific JSON field, (requires platform version 1.4.0 or later for Fargate tasks)
    API_KEY: ecs.Secret.fromSecretsManagerVersion(secret, { versionId: '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: ecs.Secret.fromSsmParameter(parameter),
  },
});
newContainer.addEnvironment('QUEUE_NAME', 'MyQueue');
newContainer.addSecret('API_KEY', ecs.Secret.fromSecretsManager(secret));
newContainer.addSecret('DB_PASSWORD', ecs.Secret.fromSecretsManager(secret, 'password'));
python
# secret: secretsmanager.Secret
# db_secret: secretsmanager.Secret
# parameter: ssm.StringParameter
# task_definition: ecs.TaskDefinition
# s3_bucket: s3.Bucket


new_container = task_definition.add_container("container",
    image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample"),
    memory_limit_mi_b=1024,
    environment={ # clear text, not for sensitive data
        "STAGE": "prod"},
    environment_files=[ # list of environment files hosted either on local disk or S3
        ecs.EnvironmentFile.from_asset("./demo-env-file.env"),
        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": ecs.Secret.from_secrets_manager(secret),
        "DB_PASSWORD": 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": ecs.Secret.from_secrets_manager_version(secret, ecs.SecretVersionInfo(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": ecs.Secret.from_ssm_parameter(parameter)}
)
new_container.add_environment("QUEUE_NAME", "MyQueue")
new_container.add_secret("API_KEY", ecs.Secret.from_secrets_manager(secret))
new_container.add_secret("DB_PASSWORD", ecs.Secret.from_secrets_manager(secret, "password"))
java
Secret secret;
Secret dbSecret;
StringParameter parameter;
TaskDefinition taskDefinition;
Bucket s3Bucket;


ContainerDefinition newContainer = taskDefinition.addContainer("container", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
        .memoryLimitMiB(1024)
        .environment(Map.of( // clear text, not for sensitive data
                "STAGE", "prod"))
        .environmentFiles(List.of(EnvironmentFile.fromAsset("./demo-env-file.env"), EnvironmentFile.fromBucket(s3Bucket, "assets/demo-env-file.env")))
        .secrets(Map.of( // Retrieved from AWS Secrets Manager or AWS Systems Manager Parameter Store at container start-up.
                "SECRET", Secret.fromSecretsManager(secret),
                "DB_PASSWORD", Secret.fromSecretsManager(dbSecret, "password"),  // Reference a specific JSON field, (requires platform version 1.4.0 or later for Fargate tasks)
                "API_KEY", Secret.fromSecretsManagerVersion(secret, SecretVersionInfo.builder().versionId("12345").build(), "apiKey"),  // Reference a specific version of the secret by its version id or version stage (requires platform version 1.4.0 or later for Fargate tasks)
                "PARAMETER", Secret.fromSsmParameter(parameter)))
        .build());
newContainer.addEnvironment("QUEUE_NAME", "MyQueue");
newContainer.addSecret("API_KEY", Secret.fromSecretsManager(secret));
newContainer.addSecret("DB_PASSWORD", Secret.fromSecretsManager(secret, "password"));
csharp
Secret secret;
Secret dbSecret;
StringParameter parameter;
TaskDefinition taskDefinition;
Bucket s3Bucket;


var newContainer = taskDefinition.AddContainer("container", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
    MemoryLimitMiB = 1024,
    Environment = new Dictionary<string, string> {  // clear text, not for sensitive data
        { "STAGE", "prod" } },
    EnvironmentFiles = new [] { EnvironmentFile.FromAsset("./demo-env-file.env"), EnvironmentFile.FromBucket(s3Bucket, "assets/demo-env-file.env") },
    Secrets = new Dictionary<string, Secret> {  // Retrieved from AWS Secrets Manager or AWS Systems Manager Parameter Store at container start-up.
        { "SECRET", Secret.FromSecretsManager(secret) },
        { "DB_PASSWORD", Secret.FromSecretsManager(dbSecret, "password") },  // Reference a specific JSON field, (requires platform version 1.4.0 or later for Fargate tasks)
        { "API_KEY", Secret.FromSecretsManagerVersion(secret, new SecretVersionInfo { VersionId = "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", Secret.FromSsmParameter(parameter) } }
});
newContainer.AddEnvironment("QUEUE_NAME", "MyQueue");
newContainer.AddSecret("API_KEY", Secret.FromSecretsManager(secret));
newContainer.AddSecret("DB_PASSWORD", Secret.FromSecretsManager(secret, "password"));
go
var secret Secret
var dbSecret Secret
var parameter StringParameter
var taskDefinition TaskDefinition
var s3Bucket Bucket


newContainer := taskDefinition.AddContainer(jsii.String("container"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	MemoryLimitMiB: jsii.Number(1024),
	Environment: map[string]*string{
		 // clear text, not for sensitive data
		"STAGE": jsii.String("prod"),
	},
	EnvironmentFiles: []EnvironmentFile{
		ecs.EnvironmentFile_FromAsset(jsii.String("./demo-env-file.env")),
		ecs.EnvironmentFile_FromBucket(s3Bucket, jsii.String("assets/demo-env-file.env")),
	},
	Secrets: map[string]Secret{
		 // Retrieved from AWS Secrets Manager or AWS Systems Manager Parameter Store at container start-up.
		"SECRET": ecs.Secret_fromSecretsManager(secret),
		"DB_PASSWORD": ecs.Secret_fromSecretsManager(dbSecret, jsii.String("password")),
		 // Reference a specific JSON field, (requires platform version 1.4.0 or later for Fargate tasks)
		"API_KEY": ecs.Secret_fromSecretsManagerVersion(secret, &SecretVersionInfo{
			"versionId": jsii.String("12345"),
		}, jsii.String("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": ecs.Secret_fromSsmParameter(parameter),
	},
})
newContainer.AddEnvironment(jsii.String("QUEUE_NAME"), jsii.String("MyQueue"))
newContainer.AddSecret(jsii.String("API_KEY"), ecs.Secret_FromSecretsManager(secret))
newContainer.AddSecret(jsii.String("DB_PASSWORD"), ecs.Secret_FromSecretsManager(secret, jsii.String("password")))

The task execution role is automatically granted read permissions on the secrets/parameters. Further details provided in the AWS documentation about specifying environment variables.

Linux parameters ​

To apply additional linux-specific options related to init process and memory management to the container, use the linuxParameters property:

ts
declare const taskDefinition: ecs.TaskDefinition;

taskDefinition.addContainer('container', {
  image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  memoryLimitMiB: 1024,
  linuxParameters: new ecs.LinuxParameters(this, 'LinuxParameters', {
    initProcessEnabled: true,
    sharedMemorySize: 1024,
    maxSwap: Size.mebibytes(5000),
    swappiness: 90,
  }),
});
python
# task_definition: ecs.TaskDefinition


task_definition.add_container("container",
    image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample"),
    memory_limit_mi_b=1024,
    linux_parameters=ecs.LinuxParameters(self, "LinuxParameters",
        init_process_enabled=True,
        shared_memory_size=1024,
        max_swap=Size.mebibytes(5000),
        swappiness=90
    )
)
java
TaskDefinition taskDefinition;


taskDefinition.addContainer("container", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
        .memoryLimitMiB(1024)
        .linuxParameters(LinuxParameters.Builder.create(this, "LinuxParameters")
                .initProcessEnabled(true)
                .sharedMemorySize(1024)
                .maxSwap(Size.mebibytes(5000))
                .swappiness(90)
                .build())
        .build());
csharp
TaskDefinition taskDefinition;


taskDefinition.AddContainer("container", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
    MemoryLimitMiB = 1024,
    LinuxParameters = new LinuxParameters(this, "LinuxParameters", new LinuxParametersProps {
        InitProcessEnabled = true,
        SharedMemorySize = 1024,
        MaxSwap = Size.Mebibytes(5000),
        Swappiness = 90
    })
});
go
var taskDefinition TaskDefinition


taskDefinition.AddContainer(jsii.String("container"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	MemoryLimitMiB: jsii.Number(1024),
	LinuxParameters: ecs.NewLinuxParameters(this, jsii.String("LinuxParameters"), &LinuxParametersProps{
		InitProcessEnabled: jsii.Boolean(true),
		SharedMemorySize: jsii.Number(1024),
		MaxSwap: awscdk.Size_Mebibytes(jsii.Number(5000)),
		Swappiness: jsii.Number(90),
	}),
})

System controls ​

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

ts
declare const taskDefinition: ecs.TaskDefinition;

taskDefinition.addContainer('container', {
  image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  memoryLimitMiB: 1024,
  systemControls: [
    {
      namespace: 'net.ipv6.conf.all.default.disable_ipv6',
      value: '1',
    },
  ],
});
python
# task_definition: ecs.TaskDefinition


task_definition.add_container("container",
    image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample"),
    memory_limit_mi_b=1024,
    system_controls=[ecs.SystemControl(
        namespace="net.ipv6.conf.all.default.disable_ipv6",
        value="1"
    )
    ]
)
java
TaskDefinition taskDefinition;


taskDefinition.addContainer("container", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
        .memoryLimitMiB(1024)
        .systemControls(List.of(SystemControl.builder()
                .namespace("net.ipv6.conf.all.default.disable_ipv6")
                .value("1")
                .build()))
        .build());
csharp
TaskDefinition taskDefinition;


taskDefinition.AddContainer("container", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
    MemoryLimitMiB = 1024,
    SystemControls = new [] { new SystemControl {
        Namespace = "net.ipv6.conf.all.default.disable_ipv6",
        Value = "1"
    } }
});
go
var taskDefinition TaskDefinition


taskDefinition.AddContainer(jsii.String("container"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	MemoryLimitMiB: jsii.Number(1024),
	SystemControls: []SystemControl{
		&SystemControl{
			Namespace: jsii.String("net.ipv6.conf.all.default.disable_ipv6"),
			Value: jsii.String("1"),
		},
	},
})

Restart policy ​

To enable a restart policy for the container, set enableRestartPolicy to true and also specify restartIgnoredExitCodes and restartAttemptPeriod if necessary.

ts
declare const taskDefinition: ecs.TaskDefinition;

taskDefinition.addContainer('container', {
  image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  enableRestartPolicy: true,
  restartIgnoredExitCodes: [0, 127],
  restartAttemptPeriod: Duration.seconds(360),
});
python
# task_definition: ecs.TaskDefinition


task_definition.add_container("container",
    image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample"),
    enable_restart_policy=True,
    restart_ignored_exit_codes=[0, 127],
    restart_attempt_period=Duration.seconds(360)
)
java
TaskDefinition taskDefinition;


taskDefinition.addContainer("container", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
        .enableRestartPolicy(true)
        .restartIgnoredExitCodes(List.of(0, 127))
        .restartAttemptPeriod(Duration.seconds(360))
        .build());
csharp
TaskDefinition taskDefinition;


taskDefinition.AddContainer("container", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
    EnableRestartPolicy = true,
    RestartIgnoredExitCodes = new [] { 0, 127 },
    RestartAttemptPeriod = Duration.Seconds(360)
});
go
var taskDefinition TaskDefinition


taskDefinition.AddContainer(jsii.String("container"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	EnableRestartPolicy: jsii.Boolean(true),
	RestartIgnoredExitCodes: []*f64{
		jsii.Number(0),
		jsii.Number(127),
	},
	RestartAttemptPeriod: awscdk.Duration_Seconds(jsii.Number(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 enableFaultInjection to true.

ts
new ecs.Ec2TaskDefinition(this, 'Ec2TaskDefinition', {
  enableFaultInjection: true,
});
python
ecs.Ec2TaskDefinition(self, "Ec2TaskDefinition",
    enable_fault_injection=True
)
java
Ec2TaskDefinition.Builder.create(this, "Ec2TaskDefinition")
        .enableFaultInjection(true)
        .build();
csharp
new Ec2TaskDefinition(this, "Ec2TaskDefinition", new Ec2TaskDefinitionProps {
    EnableFaultInjection = true
});
go
ecs.NewEc2TaskDefinition(this, jsii.String("Ec2TaskDefinition"), &Ec2TaskDefinitionProps{
	EnableFaultInjection: jsii.Boolean(true),
})

Docker labels ​

You can add labels to the container with the dockerLabels property or with the addDockerLabel method:

ts
declare const taskDefinition: ecs.TaskDefinition;

const container = taskDefinition.addContainer('cont', {
  image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  memoryLimitMiB: 1024,
  dockerLabels: {
    foo: 'bar',
  },
});

container.addDockerLabel('label', 'value');
python
# task_definition: ecs.TaskDefinition


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

container.add_docker_label("label", "value")
java
TaskDefinition taskDefinition;


ContainerDefinition container = taskDefinition.addContainer("cont", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
        .memoryLimitMiB(1024)
        .dockerLabels(Map.of(
                "foo", "bar"))
        .build());

container.addDockerLabel("label", "value");
csharp
TaskDefinition taskDefinition;


var container = taskDefinition.AddContainer("cont", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
    MemoryLimitMiB = 1024,
    DockerLabels = new Dictionary<string, string> {
        { "foo", "bar" }
    }
});

container.AddDockerLabel("label", "value");
go
var taskDefinition TaskDefinition


container := taskDefinition.AddContainer(jsii.String("cont"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	MemoryLimitMiB: jsii.Number(1024),
	DockerLabels: map[string]*string{
		"foo": jsii.String("bar"),
	},
})

container.AddDockerLabel(jsii.String("label"), jsii.String("value"))

Using Windows containers on Fargate ​

AWS Fargate supports Amazon ECS Windows containers. For more details, please see this blog post

ts
// Create a Task Definition for the Windows container to start
const taskDefinition = new ecs.FargateTaskDefinition(this, 'TaskDef', {
  runtimePlatform: {
    operatingSystemFamily: ecs.OperatingSystemFamily.WINDOWS_SERVER_2019_CORE,
    cpuArchitecture: ecs.CpuArchitecture.X86_64,
  },
  cpu: 1024,
  memoryLimitMiB: 2048,
});

taskDefinition.addContainer('windowsservercore', {
  logging: ecs.LogDriver.awsLogs({ streamPrefix: 'win-iis-on-fargate' }),
  portMappings: [{ containerPort: 80 }],
  image: ecs.ContainerImage.fromRegistry('mcr.microsoft.com/windows/servercore/iis:windowsservercore-ltsc2019'),
});
python
# Create a Task Definition for the Windows container to start
task_definition = ecs.FargateTaskDefinition(self, "TaskDef",
    runtime_platform=ecs.RuntimePlatform(
        operating_system_family=ecs.OperatingSystemFamily.WINDOWS_SERVER_2019_CORE,
        cpu_architecture=ecs.CpuArchitecture.X86_64
    ),
    cpu=1024,
    memory_limit_mi_b=2048
)

task_definition.add_container("windowsservercore",
    logging=ecs.LogDriver.aws_logs(stream_prefix="win-iis-on-fargate"),
    port_mappings=[ecs.PortMapping(container_port=80)],
    image=ecs.ContainerImage.from_registry("mcr.microsoft.com/windows/servercore/iis:windowsservercore-ltsc2019")
)
java
// Create a Task Definition for the Windows container to start
FargateTaskDefinition taskDefinition = FargateTaskDefinition.Builder.create(this, "TaskDef")
        .runtimePlatform(RuntimePlatform.builder()
                .operatingSystemFamily(OperatingSystemFamily.WINDOWS_SERVER_2019_CORE)
                .cpuArchitecture(CpuArchitecture.X86_64)
                .build())
        .cpu(1024)
        .memoryLimitMiB(2048)
        .build();

taskDefinition.addContainer("windowsservercore", ContainerDefinitionOptions.builder()
        .logging(LogDriver.awsLogs(AwsLogDriverProps.builder().streamPrefix("win-iis-on-fargate").build()))
        .portMappings(List.of(PortMapping.builder().containerPort(80).build()))
        .image(ContainerImage.fromRegistry("mcr.microsoft.com/windows/servercore/iis:windowsservercore-ltsc2019"))
        .build());
csharp
// Create a Task Definition for the Windows container to start
var taskDefinition = new FargateTaskDefinition(this, "TaskDef", new FargateTaskDefinitionProps {
    RuntimePlatform = new RuntimePlatform {
        OperatingSystemFamily = OperatingSystemFamily.WINDOWS_SERVER_2019_CORE,
        CpuArchitecture = CpuArchitecture.X86_64
    },
    Cpu = 1024,
    MemoryLimitMiB = 2048
});

taskDefinition.AddContainer("windowsservercore", new ContainerDefinitionOptions {
    Logging = LogDriver.AwsLogs(new AwsLogDriverProps { StreamPrefix = "win-iis-on-fargate" }),
    PortMappings = new [] { new PortMapping { ContainerPort = 80 } },
    Image = ContainerImage.FromRegistry("mcr.microsoft.com/windows/servercore/iis:windowsservercore-ltsc2019")
});
go
// Create a Task Definition for the Windows container to start
taskDefinition := ecs.NewFargateTaskDefinition(this, jsii.String("TaskDef"), &FargateTaskDefinitionProps{
	RuntimePlatform: &RuntimePlatform{
		OperatingSystemFamily: ecs.OperatingSystemFamily_WINDOWS_SERVER_2019_CORE(),
		CpuArchitecture: ecs.CpuArchitecture_X86_64(),
	},
	Cpu: jsii.Number(1024),
	MemoryLimitMiB: jsii.Number(2048),
})

taskDefinition.AddContainer(jsii.String("windowsservercore"), &ContainerDefinitionOptions{
	Logging: ecs.LogDriver_AwsLogs(&AwsLogDriverProps{
		StreamPrefix: jsii.String("win-iis-on-fargate"),
	}),
	PortMappings: []PortMapping{
		&PortMapping{
			ContainerPort: jsii.Number(80),
		},
	},
	Image: ecs.ContainerImage_FromRegistry(jsii.String("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:

ts
// 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.
declare const parameter: ssm.IParameter;
declare const taskDefinition: ecs.TaskDefinition;

// Domain-joined gMSA container from a SSM parameter
taskDefinition.addContainer('gmsa-domain-joined-container', {
  image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  cpu: 128,
  memoryLimitMiB: 256,
  credentialSpecs: [ecs.DomainJoinedCredentialSpec.fromSsmParameter(parameter)],
});
python
# 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: ssm.IParameter
# task_definition: ecs.TaskDefinition


# Domain-joined gMSA container from a SSM parameter
task_definition.add_container("gmsa-domain-joined-container",
    image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample"),
    cpu=128,
    memory_limit_mi_b=256,
    credential_specs=[ecs.DomainJoinedCredentialSpec.from_ssm_parameter(parameter)]
)
java
// Make sure the task definition's execution role has permissions to read from the S3 bucket or SSM parameter where the CredSpec file is stored.
IParameter parameter;
TaskDefinition taskDefinition;


// Domain-joined gMSA container from a SSM parameter
taskDefinition.addContainer("gmsa-domain-joined-container", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
        .cpu(128)
        .memoryLimitMiB(256)
        .credentialSpecs(List.of(DomainJoinedCredentialSpec.fromSsmParameter(parameter)))
        .build());
csharp
// Make sure the task definition's execution role has permissions to read from the S3 bucket or SSM parameter where the CredSpec file is stored.
IParameter parameter;
TaskDefinition taskDefinition;


// Domain-joined gMSA container from a SSM parameter
taskDefinition.AddContainer("gmsa-domain-joined-container", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
    Cpu = 128,
    MemoryLimitMiB = 256,
    CredentialSpecs = new [] { DomainJoinedCredentialSpec.FromSsmParameter(parameter) }
});
go
// 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.
var parameter IParameter
var taskDefinition TaskDefinition


// Domain-joined gMSA container from a SSM parameter
taskDefinition.AddContainer(jsii.String("gmsa-domain-joined-container"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	Cpu: jsii.Number(128),
	MemoryLimitMiB: jsii.Number(256),
	CredentialSpecs: []CredentialSpec{
		ecs.DomainJoinedCredentialSpec_FromSsmParameter(parameter),
	},
})

A domianless gMSA container looks like:

ts
// 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.
declare const bucket: s3.Bucket;
declare const taskDefinition: ecs.TaskDefinition;

// Domainless gMSA container from a S3 bucket object.
taskDefinition.addContainer('gmsa-domainless-container', {
  image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
  cpu: 128,
  memoryLimitMiB: 256,
  credentialSpecs: [ecs.DomainlessCredentialSpec.fromS3Bucket(bucket, 'credSpec')],
});
python
# 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: s3.Bucket
# task_definition: ecs.TaskDefinition


# Domainless gMSA container from a S3 bucket object.
task_definition.add_container("gmsa-domainless-container",
    image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample"),
    cpu=128,
    memory_limit_mi_b=256,
    credential_specs=[ecs.DomainlessCredentialSpec.from_s3_bucket(bucket, "credSpec")]
)
java
// Make sure the task definition's execution role has permissions to read from the S3 bucket or SSM parameter where the CredSpec file is stored.
Bucket bucket;
TaskDefinition taskDefinition;


// Domainless gMSA container from a S3 bucket object.
taskDefinition.addContainer("gmsa-domainless-container", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
        .cpu(128)
        .memoryLimitMiB(256)
        .credentialSpecs(List.of(DomainlessCredentialSpec.fromS3Bucket(bucket, "credSpec")))
        .build());
csharp
// Make sure the task definition's execution role has permissions to read from the S3 bucket or SSM parameter where the CredSpec file is stored.
Bucket bucket;
TaskDefinition taskDefinition;


// Domainless gMSA container from a S3 bucket object.
taskDefinition.AddContainer("gmsa-domainless-container", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
    Cpu = 128,
    MemoryLimitMiB = 256,
    CredentialSpecs = new [] { DomainlessCredentialSpec.FromS3Bucket(bucket, "credSpec") }
});
go
// 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.
var bucket Bucket
var taskDefinition TaskDefinition


// Domainless gMSA container from a S3 bucket object.
taskDefinition.AddContainer(jsii.String("gmsa-domainless-container"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	Cpu: jsii.Number(128),
	MemoryLimitMiB: jsii.Number(256),
	CredentialSpecs: []CredentialSpec{
		ecs.DomainlessCredentialSpec_FromS3Bucket(bucket, jsii.String("credSpec")),
	},
})

Using Graviton2 with Fargate ​

AWS Graviton2 supports AWS Fargate. For more details, please see this blog post

ts
// Create a Task Definition for running container on Graviton Runtime.
const taskDefinition = new ecs.FargateTaskDefinition(this, 'TaskDef', {
  runtimePlatform: {
    operatingSystemFamily: ecs.OperatingSystemFamily.LINUX,
    cpuArchitecture: ecs.CpuArchitecture.ARM64,
  },
  cpu: 1024,
  memoryLimitMiB: 2048,
});

taskDefinition.addContainer('webarm64', {
  logging: ecs.LogDriver.awsLogs({ streamPrefix: 'graviton2-on-fargate' }),
  portMappings: [{ containerPort: 80 }],
  image: ecs.ContainerImage.fromRegistry('public.ecr.aws/nginx/nginx:latest-arm64v8'),
});
python
# Create a Task Definition for running container on Graviton Runtime.
task_definition = ecs.FargateTaskDefinition(self, "TaskDef",
    runtime_platform=ecs.RuntimePlatform(
        operating_system_family=ecs.OperatingSystemFamily.LINUX,
        cpu_architecture=ecs.CpuArchitecture.ARM64
    ),
    cpu=1024,
    memory_limit_mi_b=2048
)

task_definition.add_container("webarm64",
    logging=ecs.LogDriver.aws_logs(stream_prefix="graviton2-on-fargate"),
    port_mappings=[ecs.PortMapping(container_port=80)],
    image=ecs.ContainerImage.from_registry("public.ecr.aws/nginx/nginx:latest-arm64v8")
)
java
// Create a Task Definition for running container on Graviton Runtime.
FargateTaskDefinition taskDefinition = FargateTaskDefinition.Builder.create(this, "TaskDef")
        .runtimePlatform(RuntimePlatform.builder()
                .operatingSystemFamily(OperatingSystemFamily.LINUX)
                .cpuArchitecture(CpuArchitecture.ARM64)
                .build())
        .cpu(1024)
        .memoryLimitMiB(2048)
        .build();

taskDefinition.addContainer("webarm64", ContainerDefinitionOptions.builder()
        .logging(LogDriver.awsLogs(AwsLogDriverProps.builder().streamPrefix("graviton2-on-fargate").build()))
        .portMappings(List.of(PortMapping.builder().containerPort(80).build()))
        .image(ContainerImage.fromRegistry("public.ecr.aws/nginx/nginx:latest-arm64v8"))
        .build());
csharp
// Create a Task Definition for running container on Graviton Runtime.
var taskDefinition = new FargateTaskDefinition(this, "TaskDef", new FargateTaskDefinitionProps {
    RuntimePlatform = new RuntimePlatform {
        OperatingSystemFamily = OperatingSystemFamily.LINUX,
        CpuArchitecture = CpuArchitecture.ARM64
    },
    Cpu = 1024,
    MemoryLimitMiB = 2048
});

taskDefinition.AddContainer("webarm64", new ContainerDefinitionOptions {
    Logging = LogDriver.AwsLogs(new AwsLogDriverProps { StreamPrefix = "graviton2-on-fargate" }),
    PortMappings = new [] { new PortMapping { ContainerPort = 80 } },
    Image = ContainerImage.FromRegistry("public.ecr.aws/nginx/nginx:latest-arm64v8")
});
go
// Create a Task Definition for running container on Graviton Runtime.
taskDefinition := ecs.NewFargateTaskDefinition(this, jsii.String("TaskDef"), &FargateTaskDefinitionProps{
	RuntimePlatform: &RuntimePlatform{
		OperatingSystemFamily: ecs.OperatingSystemFamily_LINUX(),
		CpuArchitecture: ecs.CpuArchitecture_ARM64(),
	},
	Cpu: jsii.Number(1024),
	MemoryLimitMiB: jsii.Number(2048),
})

taskDefinition.AddContainer(jsii.String("webarm64"), &ContainerDefinitionOptions{
	Logging: ecs.LogDriver_AwsLogs(&AwsLogDriverProps{
		StreamPrefix: jsii.String("graviton2-on-fargate"),
	}),
	PortMappings: []PortMapping{
		&PortMapping{
			ContainerPort: jsii.Number(80),
		},
	},
	Image: ecs.ContainerImage_FromRegistry(jsii.String("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.

ts
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;

const service = new ecs.FargateService(this, 'Service', {
  cluster,
  taskDefinition,
  desiredCount: 5,
  minHealthyPercent: 100,
  circuitBreaker: {
    enable: true,
  },
});
python
# cluster: ecs.Cluster
# task_definition: ecs.TaskDefinition


service = ecs.FargateService(self, "Service",
    cluster=cluster,
    task_definition=task_definition,
    desired_count=5,
    min_healthy_percent=100,
    circuit_breaker=ecs.DeploymentCircuitBreaker(
        enable=True
    )
)
java
Cluster cluster;
TaskDefinition taskDefinition;


FargateService service = FargateService.Builder.create(this, "Service")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .desiredCount(5)
        .minHealthyPercent(100)
        .circuitBreaker(DeploymentCircuitBreaker.builder()
                .enable(true)
                .build())
        .build();
csharp
Cluster cluster;
TaskDefinition taskDefinition;


var service = new FargateService(this, "Service", new FargateServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    DesiredCount = 5,
    MinHealthyPercent = 100,
    CircuitBreaker = new DeploymentCircuitBreaker {
        Enable = true
    }
});
go
var cluster Cluster
var taskDefinition TaskDefinition


service := ecs.NewFargateService(this, jsii.String("Service"), &FargateServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	DesiredCount: jsii.Number(5),
	MinHealthyPercent: jsii.Number(100),
	CircuitBreaker: &DeploymentCircuitBreaker{
		Enable: jsii.Boolean(true),
	},
})

ECS Anywhere service definition looks like:

ts
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;

const service = new ecs.ExternalService(this, 'Service', {
  cluster,
  taskDefinition,
  desiredCount: 5,
  minHealthyPercent: 100,
});
python
# cluster: ecs.Cluster
# task_definition: ecs.TaskDefinition


service = ecs.ExternalService(self, "Service",
    cluster=cluster,
    task_definition=task_definition,
    desired_count=5,
    min_healthy_percent=100
)
java
Cluster cluster;
TaskDefinition taskDefinition;


ExternalService service = ExternalService.Builder.create(this, "Service")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .desiredCount(5)
        .minHealthyPercent(100)
        .build();
csharp
Cluster cluster;
TaskDefinition taskDefinition;


var service = new ExternalService(this, "Service", new ExternalServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    DesiredCount = 5,
    MinHealthyPercent = 100
});
go
var cluster Cluster
var taskDefinition TaskDefinition


service := ecs.NewExternalService(this, jsii.String("Service"), &ExternalServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	DesiredCount: jsii.Number(5),
	MinHealthyPercent: jsii.Number(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 securityGroups property.

By default, the service will use the revision of the passed task definition generated when the TaskDefinition is deployed by CloudFormation. However, this may not be desired if the revision is externally managed, for example through CodeDeploy.

To set a specific revision number or the special latest revision, use the taskDefinitionRevision parameter:

ts
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;

new ecs.ExternalService(this, 'Service', {
  cluster,
  taskDefinition,
  desiredCount: 5,
  minHealthyPercent: 100,
  taskDefinitionRevision: ecs.TaskDefinitionRevision.of(1),
});

new ecs.ExternalService(this, 'Service', {
  cluster,
  taskDefinition,
  desiredCount: 5,
  minHealthyPercent: 100,
  taskDefinitionRevision: ecs.TaskDefinitionRevision.LATEST,
});
python
# cluster: ecs.Cluster
# task_definition: ecs.TaskDefinition


ecs.ExternalService(self, "Service",
    cluster=cluster,
    task_definition=task_definition,
    desired_count=5,
    min_healthy_percent=100,
    task_definition_revision=ecs.TaskDefinitionRevision.of(1)
)

ecs.ExternalService(self, "Service",
    cluster=cluster,
    task_definition=task_definition,
    desired_count=5,
    min_healthy_percent=100,
    task_definition_revision=ecs.TaskDefinitionRevision.LATEST
)
java
Cluster cluster;
TaskDefinition taskDefinition;


ExternalService.Builder.create(this, "Service")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .desiredCount(5)
        .minHealthyPercent(100)
        .taskDefinitionRevision(TaskDefinitionRevision.of(1))
        .build();

ExternalService.Builder.create(this, "Service")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .desiredCount(5)
        .minHealthyPercent(100)
        .taskDefinitionRevision(TaskDefinitionRevision.LATEST)
        .build();
csharp
Cluster cluster;
TaskDefinition taskDefinition;


new ExternalService(this, "Service", new ExternalServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    DesiredCount = 5,
    MinHealthyPercent = 100,
    TaskDefinitionRevision = TaskDefinitionRevision.Of(1)
});

new ExternalService(this, "Service", new ExternalServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    DesiredCount = 5,
    MinHealthyPercent = 100,
    TaskDefinitionRevision = TaskDefinitionRevision.LATEST
});
go
var cluster Cluster
var taskDefinition TaskDefinition


ecs.NewExternalService(this, jsii.String("Service"), &ExternalServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	DesiredCount: jsii.Number(5),
	MinHealthyPercent: jsii.Number(100),
	TaskDefinitionRevision: ecs.TaskDefinitionRevision_Of(jsii.Number(1)),
})

ecs.NewExternalService(this, jsii.String("Service"), &ExternalServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	DesiredCount: jsii.Number(5),
	MinHealthyPercent: jsii.Number(100),
	TaskDefinitionRevision: 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 circuitBreaker to enable the deployment circuit breaker which determines whether a service deployment will fail if the service can't reach a steady state. You can optionally enable rollback for automatic rollback.

See Using the deployment circuit breaker for more details.

ts
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;
const service = new ecs.FargateService(this, 'Service', {
  cluster,
  taskDefinition,
  minHealthyPercent: 100,
  circuitBreaker: {
    enable: true,
    rollback: true
  },
});
python
# cluster: ecs.Cluster
# task_definition: ecs.TaskDefinition

service = ecs.FargateService(self, "Service",
    cluster=cluster,
    task_definition=task_definition,
    min_healthy_percent=100,
    circuit_breaker=ecs.DeploymentCircuitBreaker(
        enable=True,
        rollback=True
    )
)
java
Cluster cluster;
TaskDefinition taskDefinition;

FargateService service = FargateService.Builder.create(this, "Service")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .minHealthyPercent(100)
        .circuitBreaker(DeploymentCircuitBreaker.builder()
                .enable(true)
                .rollback(true)
                .build())
        .build();
csharp
Cluster cluster;
TaskDefinition taskDefinition;

var service = new FargateService(this, "Service", new FargateServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    MinHealthyPercent = 100,
    CircuitBreaker = new DeploymentCircuitBreaker {
        Enable = true,
        Rollback = true
    }
});
go
var cluster Cluster
var taskDefinition TaskDefinition

service := ecs.NewFargateService(this, jsii.String("Service"), &FargateServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	MinHealthyPercent: jsii.Number(100),
	CircuitBreaker: &DeploymentCircuitBreaker{
		Enable: jsii.Boolean(true),
		Rollback: jsii.Boolean(true),
	},
})

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

Deployment alarms ​

Amazon ECS [deployment alarms] (https://aws.amazon.com/blogs/containers/automate-rollbacks-for-amazon-ecs-rolling-deployments-with-cloudwatch-alarms/) allow monitoring and automatically reacting to changes during a rolling update by using Amazon CloudWatch metric alarms.

Amazon ECS starts monitoring the configured deployment alarms as soon as one or more tasks of the updated service are in a running state. The deployment process continues until the primary deployment is healthy and has reached the desired count and the active deployment has been scaled down to 0. Then, the deployment remains in the IN_PROGRESS state for an additional "bake time." The length the bake time is calculated based on the evaluation periods and period of the alarms. After the bake time, if none of the alarms have been activated, then Amazon ECS considers this to be a successful update and deletes the active deployment and changes the status of the primary deployment to COMPLETED.

ts
import * as cw from 'aws-cdk-lib/aws-cloudwatch';

declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;
declare const elbAlarm: cw.Alarm;

const service = new ecs.FargateService(this, 'Service', {
  cluster,
  taskDefinition,
  minHealthyPercent: 100,
  deploymentAlarms: {
    alarmNames: [elbAlarm.alarmName],
    behavior: ecs.AlarmBehavior.ROLLBACK_ON_ALARM,
  },
});

// Defining a deployment alarm after the service has been created
const cpuAlarmName =  'MyCpuMetricAlarm';
new cw.Alarm(this, 'CPUAlarm', {
  alarmName: cpuAlarmName,
  metric: service.metricCpuUtilization(),
  evaluationPeriods: 2,
  threshold: 80,
});
service.enableDeploymentAlarms([cpuAlarmName], {
  behavior: ecs.AlarmBehavior.FAIL_ON_ALARM,
});
python
import aws_cdk.aws_cloudwatch as cw

# cluster: ecs.Cluster
# task_definition: ecs.TaskDefinition
# elb_alarm: cw.Alarm


service = ecs.FargateService(self, "Service",
    cluster=cluster,
    task_definition=task_definition,
    min_healthy_percent=100,
    deployment_alarms=ecs.DeploymentAlarmConfig(
        alarm_names=[elb_alarm.alarm_name],
        behavior=ecs.AlarmBehavior.ROLLBACK_ON_ALARM
    )
)

# Defining a deployment alarm after the service has been created
cpu_alarm_name = "MyCpuMetricAlarm"
cw.Alarm(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=ecs.AlarmBehavior.FAIL_ON_ALARM
)
java
import software.amazon.awscdk.services.cloudwatch.*;

Cluster cluster;
TaskDefinition taskDefinition;
Alarm elbAlarm;


FargateService service = FargateService.Builder.create(this, "Service")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .minHealthyPercent(100)
        .deploymentAlarms(DeploymentAlarmConfig.builder()
                .alarmNames(List.of(elbAlarm.getAlarmName()))
                .behavior(AlarmBehavior.ROLLBACK_ON_ALARM)
                .build())
        .build();

// Defining a deployment alarm after the service has been created
String cpuAlarmName = "MyCpuMetricAlarm";
Alarm.Builder.create(this, "CPUAlarm")
        .alarmName(cpuAlarmName)
        .metric(service.metricCpuUtilization())
        .evaluationPeriods(2)
        .threshold(80)
        .build();
service.enableDeploymentAlarms(List.of(cpuAlarmName), DeploymentAlarmOptions.builder()
        .behavior(AlarmBehavior.FAIL_ON_ALARM)
        .build());
csharp
using Amazon.CDK.AWS.CloudWatch;

Cluster cluster;
TaskDefinition taskDefinition;
Alarm elbAlarm;


var service = new FargateService(this, "Service", new FargateServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    MinHealthyPercent = 100,
    DeploymentAlarms = new DeploymentAlarmConfig {
        AlarmNames = new [] { elbAlarm.AlarmName },
        Behavior = AlarmBehavior.ROLLBACK_ON_ALARM
    }
});

// Defining a deployment alarm after the service has been created
var cpuAlarmName = "MyCpuMetricAlarm";
new Alarm(this, "CPUAlarm", new AlarmProps {
    AlarmName = cpuAlarmName,
    Metric = service.MetricCpuUtilization(),
    EvaluationPeriods = 2,
    Threshold = 80
});
service.EnableDeploymentAlarms(new [] { cpuAlarmName }, new DeploymentAlarmOptions {
    Behavior = AlarmBehavior.FAIL_ON_ALARM
});
go
import cw "github.com/aws/aws-cdk-go/awscdk"

var cluster Cluster
var taskDefinition TaskDefinition
var elbAlarm Alarm


service := ecs.NewFargateService(this, jsii.String("Service"), &FargateServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	MinHealthyPercent: jsii.Number(100),
	DeploymentAlarms: &DeploymentAlarmConfig{
		AlarmNames: []*string{
			elbAlarm.alarmName,
		},
		Behavior: ecs.AlarmBehavior_ROLLBACK_ON_ALARM,
	},
})

// Defining a deployment alarm after the service has been created
cpuAlarmName := "MyCpuMetricAlarm"
cw.NewAlarm(this, jsii.String("CPUAlarm"), &AlarmProps{
	AlarmName: cpuAlarmName,
	Metric: service.MetricCpuUtilization(),
	EvaluationPeriods: jsii.Number(2),
	Threshold: jsii.Number(80),
})
service.EnableDeploymentAlarms([]*string{
	cpuAlarmName,
}, &DeploymentAlarmOptions{
	Behavior: ecs.AlarmBehavior_FAIL_ON_ALARM,
})

Note: Deployment alarms are only available when deploymentController is set to DeploymentControllerType.ECS, which is the default.

Troubleshooting circular dependencies ​

I saw this info message during synth time. What do I do?

text
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 metricCpuUtilization() or similar methods. Create the metric object separately by referencing the service metrics using this name.

Option 1, defining a physical name for the alarm:

ts
import * as cw from 'aws-cdk-lib/aws-cloudwatch';

declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;

const service = new ecs.FargateService(this, 'Service', {
  cluster,
  taskDefinition,
});

const cpuAlarmName =  'MyCpuMetricAlarm';
const myAlarm = new cw.Alarm(this, 'CPUAlarm', {
  alarmName: cpuAlarmName,
  metric: service.metricCpuUtilization(),
  evaluationPeriods: 2,
  threshold: 80,
});

// Using `myAlarm.alarmName` here will cause a circular dependency
service.enableDeploymentAlarms([cpuAlarmName], {
  behavior: ecs.AlarmBehavior.FAIL_ON_ALARM,
});
python
import aws_cdk.aws_cloudwatch as cw

# cluster: ecs.Cluster
# task_definition: ecs.TaskDefinition


service = ecs.FargateService(self, "Service",
    cluster=cluster,
    task_definition=task_definition
)

cpu_alarm_name = "MyCpuMetricAlarm"
my_alarm = cw.Alarm(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=ecs.AlarmBehavior.FAIL_ON_ALARM
)
java
import software.amazon.awscdk.services.cloudwatch.*;

Cluster cluster;
TaskDefinition taskDefinition;


FargateService service = FargateService.Builder.create(this, "Service")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .build();

String cpuAlarmName = "MyCpuMetricAlarm";
Alarm myAlarm = Alarm.Builder.create(this, "CPUAlarm")
        .alarmName(cpuAlarmName)
        .metric(service.metricCpuUtilization())
        .evaluationPeriods(2)
        .threshold(80)
        .build();

// Using `myAlarm.alarmName` here will cause a circular dependency
service.enableDeploymentAlarms(List.of(cpuAlarmName), DeploymentAlarmOptions.builder()
        .behavior(AlarmBehavior.FAIL_ON_ALARM)
        .build());
csharp
using Amazon.CDK.AWS.CloudWatch;

Cluster cluster;
TaskDefinition taskDefinition;


var service = new FargateService(this, "Service", new FargateServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition
});

var cpuAlarmName = "MyCpuMetricAlarm";
var myAlarm = new Alarm(this, "CPUAlarm", new AlarmProps {
    AlarmName = cpuAlarmName,
    Metric = service.MetricCpuUtilization(),
    EvaluationPeriods = 2,
    Threshold = 80
});

// Using `myAlarm.alarmName` here will cause a circular dependency
service.EnableDeploymentAlarms(new [] { cpuAlarmName }, new DeploymentAlarmOptions {
    Behavior = AlarmBehavior.FAIL_ON_ALARM
});
go
import cw "github.com/aws/aws-cdk-go/awscdk"

var cluster Cluster
var taskDefinition TaskDefinition


service := ecs.NewFargateService(this, jsii.String("Service"), &FargateServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
})

cpuAlarmName := "MyCpuMetricAlarm"
myAlarm := cw.NewAlarm(this, jsii.String("CPUAlarm"), &AlarmProps{
	AlarmName: cpuAlarmName,
	Metric: service.MetricCpuUtilization(),
	EvaluationPeriods: jsii.Number(2),
	Threshold: jsii.Number(80),
})

// Using `myAlarm.alarmName` here will cause a circular dependency
service.EnableDeploymentAlarms([]*string{
	cpuAlarmName,
}, &DeploymentAlarmOptions{
	Behavior: ecs.AlarmBehavior_FAIL_ON_ALARM,
})

Option 2, defining a physical name for the service:

ts
import * as cw from 'aws-cdk-lib/aws-cloudwatch';

declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;
const serviceName = 'MyFargateService';
const service = new ecs.FargateService(this, 'Service', {
  serviceName,
  cluster,
  taskDefinition,
  minHealthyPercent: 100,
});

const cpuMetric = new cw.Metric({
  metricName: 'CPUUtilization',
  namespace: 'AWS/ECS',
  period: Duration.minutes(5),
  statistic: 'Average',
  dimensionsMap: {
    ClusterName: cluster.clusterName,
    // Using `service.serviceName` here will cause a circular dependency
    ServiceName: serviceName,
  },
});
const myAlarm = new cw.Alarm(this, 'CPUAlarm', {
  alarmName: 'cpuAlarmName',
  metric: cpuMetric,
  evaluationPeriods: 2,
  threshold: 80,
});

service.enableDeploymentAlarms([myAlarm.alarmName], {
  behavior: ecs.AlarmBehavior.FAIL_ON_ALARM,
});
python
import aws_cdk.aws_cloudwatch as cw

# cluster: ecs.Cluster
# task_definition: ecs.TaskDefinition

service_name = "MyFargateService"
service = ecs.FargateService(self, "Service",
    service_name=service_name,
    cluster=cluster,
    task_definition=task_definition,
    min_healthy_percent=100
)

cpu_metric = cw.Metric(
    metric_name="CPUUtilization",
    namespace="AWS/ECS",
    period=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 = cw.Alarm(self, "CPUAlarm",
    alarm_name="cpuAlarmName",
    metric=cpu_metric,
    evaluation_periods=2,
    threshold=80
)

service.enable_deployment_alarms([my_alarm.alarm_name],
    behavior=ecs.AlarmBehavior.FAIL_ON_ALARM
)
java
import software.amazon.awscdk.services.cloudwatch.*;

Cluster cluster;
TaskDefinition taskDefinition;

String serviceName = "MyFargateService";
FargateService service = FargateService.Builder.create(this, "Service")
        .serviceName(serviceName)
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .minHealthyPercent(100)
        .build();

Metric cpuMetric = Metric.Builder.create()
        .metricName("CPUUtilization")
        .namespace("AWS/ECS")
        .period(Duration.minutes(5))
        .statistic("Average")
        .dimensionsMap(Map.of(
                "ClusterName", cluster.getClusterName(),
                // Using `service.serviceName` here will cause a circular dependency
                "ServiceName", serviceName))
        .build();
Alarm myAlarm = Alarm.Builder.create(this, "CPUAlarm")
        .alarmName("cpuAlarmName")
        .metric(cpuMetric)
        .evaluationPeriods(2)
        .threshold(80)
        .build();

service.enableDeploymentAlarms(List.of(myAlarm.getAlarmName()), DeploymentAlarmOptions.builder()
        .behavior(AlarmBehavior.FAIL_ON_ALARM)
        .build());
csharp
using Amazon.CDK.AWS.CloudWatch;

Cluster cluster;
TaskDefinition taskDefinition;

var serviceName = "MyFargateService";
var service = new FargateService(this, "Service", new FargateServiceProps {
    ServiceName = serviceName,
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    MinHealthyPercent = 100
});

var cpuMetric = new Metric(new MetricProps {
    MetricName = "CPUUtilization",
    Namespace = "AWS/ECS",
    Period = Duration.Minutes(5),
    Statistic = "Average",
    DimensionsMap = new Dictionary<string, string> {
        { "ClusterName", cluster.ClusterName },
        // Using `service.serviceName` here will cause a circular dependency
        { "ServiceName", serviceName }
    }
});
var myAlarm = new Alarm(this, "CPUAlarm", new AlarmProps {
    AlarmName = "cpuAlarmName",
    Metric = cpuMetric,
    EvaluationPeriods = 2,
    Threshold = 80
});

service.EnableDeploymentAlarms(new [] { myAlarm.AlarmName }, new DeploymentAlarmOptions {
    Behavior = AlarmBehavior.FAIL_ON_ALARM
});
go
import "github.com/aws/aws-cdk-go/awscdk"

var cluster Cluster
var taskDefinition TaskDefinition

serviceName := "MyFargateService"
service := ecs.NewFargateService(this, jsii.String("Service"), &FargateServiceProps{
	ServiceName: jsii.String(ServiceName),
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	MinHealthyPercent: jsii.Number(100),
})

cpuMetric := cw.NewMetric(&MetricProps{
	MetricName: jsii.String("CPUUtilization"),
	Namespace: jsii.String("AWS/ECS"),
	Period: awscdk.Duration_Minutes(jsii.Number(5)),
	Statistic: jsii.String("Average"),
	DimensionsMap: map[string]*string{
		"ClusterName": cluster.clusterName,
		// Using `service.serviceName` here will cause a circular dependency
		"ServiceName": serviceName,
	},
})
myAlarm := cw.NewAlarm(this, jsii.String("CPUAlarm"), &AlarmProps{
	AlarmName: jsii.String("cpuAlarmName"),
	Metric: cpuMetric,
	EvaluationPeriods: jsii.Number(2),
	Threshold: jsii.Number(80),
})

service.EnableDeploymentAlarms([]*string{
	myAlarm.alarmName,
}, &DeploymentAlarmOptions{
	Behavior: 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:

ts
declare const vpc: ec2.Vpc;
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;
const service = new ecs.FargateService(this, 'Service', { cluster, taskDefinition, minHealthyPercent: 100 });

const lb = new elbv2.ApplicationLoadBalancer(this, 'LB', { vpc, internetFacing: true });
const listener = lb.addListener('Listener', { port: 80 });
const targetGroup1 = listener.addTargets('ECS1', {
  port: 80,
  targets: [service],
});
const targetGroup2 = listener.addTargets('ECS2', {
  port: 80,
  targets: [service.loadBalancerTarget({
    containerName: 'MyContainer',
    containerPort: 8080
  })],
});
python
# vpc: ec2.Vpc
# cluster: ecs.Cluster
# task_definition: ecs.TaskDefinition

service = ecs.FargateService(self, "Service", cluster=cluster, task_definition=task_definition, min_healthy_percent=100)

lb = elbv2.ApplicationLoadBalancer(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
    )]
)
java
Vpc vpc;
Cluster cluster;
TaskDefinition taskDefinition;

FargateService service = FargateService.Builder.create(this, "Service").cluster(cluster).taskDefinition(taskDefinition).minHealthyPercent(100).build();

ApplicationLoadBalancer lb = ApplicationLoadBalancer.Builder.create(this, "LB").vpc(vpc).internetFacing(true).build();
ApplicationListener listener = lb.addListener("Listener", BaseApplicationListenerProps.builder().port(80).build());
ApplicationTargetGroup targetGroup1 = listener.addTargets("ECS1", AddApplicationTargetsProps.builder()
        .port(80)
        .targets(List.of(service))
        .build());
ApplicationTargetGroup targetGroup2 = listener.addTargets("ECS2", AddApplicationTargetsProps.builder()
        .port(80)
        .targets(List.of(service.loadBalancerTarget(LoadBalancerTargetOptions.builder()
                .containerName("MyContainer")
                .containerPort(8080)
                .build())))
        .build());
csharp
Vpc vpc;
Cluster cluster;
TaskDefinition taskDefinition;

var service = new FargateService(this, "Service", new FargateServiceProps { Cluster = cluster, TaskDefinition = taskDefinition, MinHealthyPercent = 100 });

var lb = new ApplicationLoadBalancer(this, "LB", new ApplicationLoadBalancerProps { Vpc = vpc, InternetFacing = true });
var listener = lb.AddListener("Listener", new BaseApplicationListenerProps { Port = 80 });
var targetGroup1 = listener.AddTargets("ECS1", new AddApplicationTargetsProps {
    Port = 80,
    Targets = new [] { service }
});
var targetGroup2 = listener.AddTargets("ECS2", new AddApplicationTargetsProps {
    Port = 80,
    Targets = new [] { service.LoadBalancerTarget(new LoadBalancerTargetOptions {
        ContainerName = "MyContainer",
        ContainerPort = 8080
    }) }
});
go
var vpc Vpc
var cluster Cluster
var taskDefinition TaskDefinition

service := ecs.NewFargateService(this, jsii.String("Service"), &FargateServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	MinHealthyPercent: jsii.Number(100),
})

lb := elbv2.NewApplicationLoadBalancer(this, jsii.String("LB"), &ApplicationLoadBalancerProps{
	Vpc: Vpc,
	InternetFacing: jsii.Boolean(true),
})
listener := lb.AddListener(jsii.String("Listener"), &BaseApplicationListenerProps{
	Port: jsii.Number(80),
})
targetGroup1 := listener.AddTargets(jsii.String("ECS1"), &AddApplicationTargetsProps{
	Port: jsii.Number(80),
	Targets: []IApplicationLoadBalancerTarget{
		service,
	},
})
targetGroup2 := listener.AddTargets(jsii.String("ECS2"), &AddApplicationTargetsProps{
	Port: jsii.Number(80),
	Targets: []IApplicationLoadBalancerTarget{
		service.LoadBalancerTarget(&LoadBalancerTargetOptions{
			ContainerName: jsii.String("MyContainer"),
			ContainerPort: jsii.Number(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.

ts
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;
declare const vpc: ec2.Vpc;
const service = new ecs.FargateService(this, 'Service', { cluster, taskDefinition, minHealthyPercent: 100 });

const lb = new elbv2.ApplicationLoadBalancer(this, 'LB', { vpc, internetFacing: true });
const listener = lb.addListener('Listener', { port: 80 });
service.registerLoadBalancerTargets(
  {
    containerName: 'web',
    containerPort: 80,
    newTargetGroupId: 'ECS',
    listener: ecs.ListenerConfig.applicationListener(listener, {
      protocol: elbv2.ApplicationProtocol.HTTPS
    }),
  },
);
python
# cluster: ecs.Cluster
# task_definition: ecs.TaskDefinition
# vpc: ec2.Vpc

service = ecs.FargateService(self, "Service", cluster=cluster, task_definition=task_definition, min_healthy_percent=100)

lb = elbv2.ApplicationLoadBalancer(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=ecs.ListenerConfig.application_listener(listener,
        protocol=elbv2.ApplicationProtocol.HTTPS
    )
)
java
Cluster cluster;
TaskDefinition taskDefinition;
Vpc vpc;

FargateService service = FargateService.Builder.create(this, "Service").cluster(cluster).taskDefinition(taskDefinition).minHealthyPercent(100).build();

ApplicationLoadBalancer lb = ApplicationLoadBalancer.Builder.create(this, "LB").vpc(vpc).internetFacing(true).build();
ApplicationListener listener = lb.addListener("Listener", BaseApplicationListenerProps.builder().port(80).build());
service.registerLoadBalancerTargets(EcsTarget.builder()
        .containerName("web")
        .containerPort(80)
        .newTargetGroupId("ECS")
        .listener(ListenerConfig.applicationListener(listener, AddApplicationTargetsProps.builder()
                .protocol(ApplicationProtocol.HTTPS)
                .build()))
        .build());
csharp
Cluster cluster;
TaskDefinition taskDefinition;
Vpc vpc;

var service = new FargateService(this, "Service", new FargateServiceProps { Cluster = cluster, TaskDefinition = taskDefinition, MinHealthyPercent = 100 });

var lb = new ApplicationLoadBalancer(this, "LB", new ApplicationLoadBalancerProps { Vpc = vpc, InternetFacing = true });
var listener = lb.AddListener("Listener", new BaseApplicationListenerProps { Port = 80 });
service.RegisterLoadBalancerTargets(new EcsTarget {
    ContainerName = "web",
    ContainerPort = 80,
    NewTargetGroupId = "ECS",
    Listener = ListenerConfig.ApplicationListener(listener, new AddApplicationTargetsProps {
        Protocol = ApplicationProtocol.HTTPS
    })
});
go
var cluster Cluster
var taskDefinition TaskDefinition
var vpc Vpc

service := ecs.NewFargateService(this, jsii.String("Service"), &FargateServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	MinHealthyPercent: jsii.Number(100),
})

lb := elbv2.NewApplicationLoadBalancer(this, jsii.String("LB"), &ApplicationLoadBalancerProps{
	Vpc: Vpc,
	InternetFacing: jsii.Boolean(true),
})
listener := lb.AddListener(jsii.String("Listener"), &BaseApplicationListenerProps{
	Port: jsii.Number(80),
})
service.RegisterLoadBalancerTargets(&EcsTarget{
	ContainerName: jsii.String("web"),
	ContainerPort: jsii.Number(80),
	NewTargetGroupId: jsii.String("ECS"),
	Listener: ecs.ListenerConfig_ApplicationListener(listener, &AddApplicationTargetsProps{
		Protocol: elbv2.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:

ts
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;
declare const vpc: ec2.Vpc;
const service = new ecs.Ec2Service(this, 'Service', { cluster, taskDefinition, minHealthyPercent: 100 });

const lb = new elb.LoadBalancer(this, 'LB', { vpc });
lb.addListener({ externalPort: 80 });
lb.addTarget(service);
python
# cluster: ecs.Cluster
# task_definition: ecs.TaskDefinition
# vpc: ec2.Vpc

service = ecs.Ec2Service(self, "Service", cluster=cluster, task_definition=task_definition, min_healthy_percent=100)

lb = elb.LoadBalancer(self, "LB", vpc=vpc)
lb.add_listener(external_port=80)
lb.add_target(service)
java
Cluster cluster;
TaskDefinition taskDefinition;
Vpc vpc;

Ec2Service service = Ec2Service.Builder.create(this, "Service").cluster(cluster).taskDefinition(taskDefinition).minHealthyPercent(100).build();

LoadBalancer lb = LoadBalancer.Builder.create(this, "LB").vpc(vpc).build();
lb.addListener(LoadBalancerListener.builder().externalPort(80).build());
lb.addTarget(service);
csharp
Cluster cluster;
TaskDefinition taskDefinition;
Vpc vpc;

var service = new Ec2Service(this, "Service", new Ec2ServiceProps { Cluster = cluster, TaskDefinition = taskDefinition, MinHealthyPercent = 100 });

var lb = new LoadBalancer(this, "LB", new LoadBalancerProps { Vpc = vpc });
lb.AddListener(new LoadBalancerListener { ExternalPort = 80 });
lb.AddTarget(service);
go
var cluster Cluster
var taskDefinition TaskDefinition
var vpc Vpc

service := ecs.NewEc2Service(this, jsii.String("Service"), &Ec2ServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	MinHealthyPercent: jsii.Number(100),
})

lb := elb.NewLoadBalancer(this, jsii.String("LB"), &LoadBalancerProps{
	Vpc: Vpc,
})
lb.AddListener(&LoadBalancerListener{
	ExternalPort: jsii.Number(80),
})
lb.AddTarget(service)

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

ts
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;
declare const vpc: ec2.Vpc;
const service = new ecs.Ec2Service(this, 'Service', { cluster, taskDefinition, minHealthyPercent: 100 });

const lb = new elb.LoadBalancer(this, 'LB', { vpc });
lb.addListener({ externalPort: 80 });
lb.addTarget(service.loadBalancerTarget({
  containerName: 'MyContainer',
  containerPort: 80,
}));
python
# cluster: ecs.Cluster
# task_definition: ecs.TaskDefinition
# vpc: ec2.Vpc

service = ecs.Ec2Service(self, "Service", cluster=cluster, task_definition=task_definition, min_healthy_percent=100)

lb = elb.LoadBalancer(self, "LB", vpc=vpc)
lb.add_listener(external_port=80)
lb.add_target(service.load_balancer_target(
    container_name="MyContainer",
    container_port=80
))
java
Cluster cluster;
TaskDefinition taskDefinition;
Vpc vpc;

Ec2Service service = Ec2Service.Builder.create(this, "Service").cluster(cluster).taskDefinition(taskDefinition).minHealthyPercent(100).build();

LoadBalancer lb = LoadBalancer.Builder.create(this, "LB").vpc(vpc).build();
lb.addListener(LoadBalancerListener.builder().externalPort(80).build());
lb.addTarget(service.loadBalancerTarget(LoadBalancerTargetOptions.builder()
        .containerName("MyContainer")
        .containerPort(80)
        .build()));
csharp
Cluster cluster;
TaskDefinition taskDefinition;
Vpc vpc;

var service = new Ec2Service(this, "Service", new Ec2ServiceProps { Cluster = cluster, TaskDefinition = taskDefinition, MinHealthyPercent = 100 });

var lb = new LoadBalancer(this, "LB", new LoadBalancerProps { Vpc = vpc });
lb.AddListener(new LoadBalancerListener { ExternalPort = 80 });
lb.AddTarget(service.LoadBalancerTarget(new LoadBalancerTargetOptions {
    ContainerName = "MyContainer",
    ContainerPort = 80
}));
go
var cluster Cluster
var taskDefinition TaskDefinition
var vpc Vpc

service := ecs.NewEc2Service(this, jsii.String("Service"), &Ec2ServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	MinHealthyPercent: jsii.Number(100),
})

lb := elb.NewLoadBalancer(this, jsii.String("LB"), &LoadBalancerProps{
	Vpc: Vpc,
})
lb.AddListener(&LoadBalancerListener{
	ExternalPort: jsii.Number(80),
})
lb.AddTarget(service.LoadBalancerTarget(&LoadBalancerTargetOptions{
	ContainerName: jsii.String("MyContainer"),
	ContainerPort: jsii.Number(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:

  • LoadBalancedFargateService
  • LoadBalancedEc2Service

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.

ts
declare const cluster: ecs.Cluster;

// Import service from EC2 service attributes
const ec2ServiceFromAttributes = ecs.Ec2Service.fromEc2ServiceAttributes(this, 'Ec2ServiceFromAttributes', {
  serviceArn: 'arn:aws:ecs:us-west-2:123456789012:service/my-http-service',
  cluster,
});

// Import service from EC2 service ARN
const ec2ServiceFromArn = ecs.Ec2Service.fromEc2ServiceArn(this, 'Ec2ServiceFromArn', 'arn:aws:ecs:us-west-2:123456789012:service/my-http-service');

// Import service from Fargate service attributes
const fargateServiceFromAttributes = ecs.FargateService.fromFargateServiceAttributes(this, 'FargateServiceFromAttributes', {
  serviceArn: 'arn:aws:ecs:us-west-2:123456789012:service/my-http-service',
  cluster,
});

// Import service from Fargate service ARN
const fargateServiceFromArn = ecs.FargateService.fromFargateServiceArn(this, 'FargateServiceFromArn', 'arn:aws:ecs:us-west-2:123456789012:service/my-http-service');
python
# cluster: ecs.Cluster


# Import service from EC2 service attributes
ec2_service_from_attributes = ecs.Ec2Service.from_ec2_service_attributes(self, "Ec2ServiceFromAttributes",
    service_arn="arn:aws:ecs:us-west-2:123456789012:service/my-http-service",
    cluster=cluster
)

# Import service from EC2 service ARN
ec2_service_from_arn = ecs.Ec2Service.from_ec2_service_arn(self, "Ec2ServiceFromArn", "arn:aws:ecs:us-west-2:123456789012:service/my-http-service")

# Import service from Fargate service attributes
fargate_service_from_attributes = ecs.FargateService.from_fargate_service_attributes(self, "FargateServiceFromAttributes",
    service_arn="arn:aws:ecs:us-west-2:123456789012:service/my-http-service",
    cluster=cluster
)

# Import service from Fargate service ARN
fargate_service_from_arn = ecs.FargateService.from_fargate_service_arn(self, "FargateServiceFromArn", "arn:aws:ecs:us-west-2:123456789012:service/my-http-service")
java
Cluster cluster;


// Import service from EC2 service attributes
IBaseService ec2ServiceFromAttributes = Ec2Service.fromEc2ServiceAttributes(this, "Ec2ServiceFromAttributes", Ec2ServiceAttributes.builder()
        .serviceArn("arn:aws:ecs:us-west-2:123456789012:service/my-http-service")
        .cluster(cluster)
        .build());

// Import service from EC2 service ARN
IEc2Service ec2ServiceFromArn = Ec2Service.fromEc2ServiceArn(this, "Ec2ServiceFromArn", "arn:aws:ecs:us-west-2:123456789012:service/my-http-service");

// Import service from Fargate service attributes
IBaseService fargateServiceFromAttributes = FargateService.fromFargateServiceAttributes(this, "FargateServiceFromAttributes", FargateServiceAttributes.builder()
        .serviceArn("arn:aws:ecs:us-west-2:123456789012:service/my-http-service")
        .cluster(cluster)
        .build());

// Import service from Fargate service ARN
IFargateService fargateServiceFromArn = FargateService.fromFargateServiceArn(this, "FargateServiceFromArn", "arn:aws:ecs:us-west-2:123456789012:service/my-http-service");
csharp
Cluster cluster;


// Import service from EC2 service attributes
var ec2ServiceFromAttributes = Ec2Service.FromEc2ServiceAttributes(this, "Ec2ServiceFromAttributes", new Ec2ServiceAttributes {
    ServiceArn = "arn:aws:ecs:us-west-2:123456789012:service/my-http-service",
    Cluster = cluster
});

// Import service from EC2 service ARN
var ec2ServiceFromArn = Ec2Service.FromEc2ServiceArn(this, "Ec2ServiceFromArn", "arn:aws:ecs:us-west-2:123456789012:service/my-http-service");

// Import service from Fargate service attributes
var fargateServiceFromAttributes = FargateService.FromFargateServiceAttributes(this, "FargateServiceFromAttributes", new FargateServiceAttributes {
    ServiceArn = "arn:aws:ecs:us-west-2:123456789012:service/my-http-service",
    Cluster = cluster
});

// Import service from Fargate service ARN
var fargateServiceFromArn = FargateService.FromFargateServiceArn(this, "FargateServiceFromArn", "arn:aws:ecs:us-west-2:123456789012:service/my-http-service");
go
var cluster Cluster


// Import service from EC2 service attributes
ec2ServiceFromAttributes := ecs.Ec2Service_FromEc2ServiceAttributes(this, jsii.String("Ec2ServiceFromAttributes"), &Ec2ServiceAttributes{
	ServiceArn: jsii.String("arn:aws:ecs:us-west-2:123456789012:service/my-http-service"),
	Cluster: Cluster,
})

// Import service from EC2 service ARN
ec2ServiceFromArn := ecs.Ec2Service_FromEc2ServiceArn(this, jsii.String("Ec2ServiceFromArn"), jsii.String("arn:aws:ecs:us-west-2:123456789012:service/my-http-service"))

// Import service from Fargate service attributes
fargateServiceFromAttributes := ecs.FargateService_FromFargateServiceAttributes(this, jsii.String("FargateServiceFromAttributes"), &FargateServiceAttributes{
	ServiceArn: jsii.String("arn:aws:ecs:us-west-2:123456789012:service/my-http-service"),
	Cluster: Cluster,
})

// Import service from Fargate service ARN
fargateServiceFromArn := ecs.FargateService_FromFargateServiceArn(this, jsii.String("FargateServiceFromArn"), jsii.String("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.

ts
declare const vpc: ec2.Vpc;
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;

const service = new ecs.FargateService(this, 'Service', {
  cluster,
  taskDefinition,
  // Fargate will try to ensure an even spread of newly launched tasks across
  // all AZs corresponding to the public subnets of the VPC.
  vpcSubnets: { subnetType: ec2.SubnetType.PUBLIC },
});
python
# vpc: ec2.Vpc
# cluster: ecs.Cluster
# task_definition: ecs.TaskDefinition


service = ecs.FargateService(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=ec2.SubnetSelection(subnet_type=ec2.SubnetType.PUBLIC)
)
java
Vpc vpc;
Cluster cluster;
TaskDefinition taskDefinition;


FargateService service = FargateService.Builder.create(this, "Service")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        // Fargate will try to ensure an even spread of newly launched tasks across
        // all AZs corresponding to the public subnets of the VPC.
        .vpcSubnets(SubnetSelection.builder().subnetType(SubnetType.PUBLIC).build())
        .build();
csharp
Vpc vpc;
Cluster cluster;
TaskDefinition taskDefinition;


var service = new FargateService(this, "Service", new FargateServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    // Fargate will try to ensure an even spread of newly launched tasks across
    // all AZs corresponding to the public subnets of the VPC.
    VpcSubnets = new SubnetSelection { SubnetType = SubnetType.PUBLIC }
});
go
var vpc Vpc
var cluster Cluster
var taskDefinition TaskDefinition


service := ecs.NewFargateService(this, jsii.String("Service"), &FargateServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	// Fargate will try to ensure an even spread of newly launched tasks across
	// all AZs corresponding to the public subnets of the VPC.
	VpcSubnets: &SubnetSelection{
		SubnetType: 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:

ts
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;

const service = new ecs.FargateService(this, 'Service', {
  cluster,
  taskDefinition,
  availabilityZoneRebalancing: ecs.AvailabilityZoneRebalancing.ENABLED,
});
python
# cluster: ecs.Cluster
# task_definition: ecs.TaskDefinition


service = ecs.FargateService(self, "Service",
    cluster=cluster,
    task_definition=task_definition,
    availability_zone_rebalancing=ecs.AvailabilityZoneRebalancing.ENABLED
)
java
Cluster cluster;
TaskDefinition taskDefinition;


FargateService service = FargateService.Builder.create(this, "Service")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .availabilityZoneRebalancing(AvailabilityZoneRebalancing.ENABLED)
        .build();
csharp
Cluster cluster;
TaskDefinition taskDefinition;


var service = new FargateService(this, "Service", new FargateServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    AvailabilityZoneRebalancing = AvailabilityZoneRebalancing.ENABLED
});
go
var cluster Cluster
var taskDefinition TaskDefinition


service := ecs.NewFargateService(this, jsii.String("Service"), &FargateServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	AvailabilityZoneRebalancing: ecs.AvailabilityZoneRebalancing_ENABLED,
})

Availability Zone rebalancing works in the following configurations:

  • Services that use the Replica strategy.
  • Services that specify Availability Zone spread as the first task placement strategy, or do not specify a placement strategy.

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

  • Uses the Daemon strategy.
  • Uses the EXTERNAL launch type (ECSAnywhere).
  • Uses 100% for the maximumPercent value.
  • Uses a Classic Load Balancer.
  • Uses the attribute:ecs.availability-zone as a task placement constraint.

Task Auto-Scaling ​

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

ts
declare const target: elbv2.ApplicationTargetGroup;
declare const service: ecs.BaseService;
const scaling = service.autoScaleTaskCount({ maxCapacity: 10 });
scaling.scaleOnCpuUtilization('CpuScaling', {
  targetUtilizationPercent: 50,
});

scaling.scaleOnRequestCount('RequestScaling', {
  requestsPerTarget: 10000,
  targetGroup: target,
});
python
# target: elbv2.ApplicationTargetGroup
# service: 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
)
java
ApplicationTargetGroup target;
BaseService service;

ScalableTaskCount scaling = service.autoScaleTaskCount(EnableScalingProps.builder().maxCapacity(10).build());
scaling.scaleOnCpuUtilization("CpuScaling", CpuUtilizationScalingProps.builder()
        .targetUtilizationPercent(50)
        .build());

scaling.scaleOnRequestCount("RequestScaling", RequestCountScalingProps.builder()
        .requestsPerTarget(10000)
        .targetGroup(target)
        .build());
csharp
ApplicationTargetGroup target;
BaseService service;

var scaling = service.AutoScaleTaskCount(new EnableScalingProps { MaxCapacity = 10 });
scaling.ScaleOnCpuUtilization("CpuScaling", new CpuUtilizationScalingProps {
    TargetUtilizationPercent = 50
});

scaling.ScaleOnRequestCount("RequestScaling", new RequestCountScalingProps {
    RequestsPerTarget = 10000,
    TargetGroup = target
});
go
var target ApplicationTargetGroup
var service BaseService

scaling := service.AutoScaleTaskCount(&EnableScalingProps{
	MaxCapacity: jsii.Number(10),
})
scaling.ScaleOnCpuUtilization(jsii.String("CpuScaling"), &CpuUtilizationScalingProps{
	TargetUtilizationPercent: jsii.Number(50),
})

scaling.ScaleOnRequestCount(jsii.String("RequestScaling"), &RequestCountScalingProps{
	RequestsPerTarget: jsii.Number(10000),
	TargetGroup: target,
})

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

To scale on SQS queue depth, see Autoscaling consumers on queue depth.

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:

ts
declare const cluster: ecs.Cluster;
// Create a Task Definition for the container to start
const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');
taskDefinition.addContainer('TheContainer', {
  image: ecs.ContainerImage.fromAsset(path.resolve(__dirname, '..', 'eventhandler-image')),
  memoryLimitMiB: 256,
  logging: new ecs.AwsLogDriver({ streamPrefix: 'EventDemo', mode: ecs.AwsLogDriverMode.NON_BLOCKING }),
});

// An Rule that describes the event trigger (in this case a scheduled run)
const rule = new events.Rule(this, 'Rule', {
  schedule: events.Schedule.expression('rate(1 minute)'),
});

// Pass an environment variable to the container 'TheContainer' in the task
rule.addTarget(new targets.EcsTask({
  cluster,
  taskDefinition,
  taskCount: 1,
  containerOverrides: [{
    containerName: 'TheContainer',
    environment: [{
      name: 'I_WAS_TRIGGERED',
      value: 'From CloudWatch Events'
    }],
  }],
}));
python
# cluster: ecs.Cluster

# Create a Task Definition for the container to start
task_definition = ecs.Ec2TaskDefinition(self, "TaskDef")
task_definition.add_container("TheContainer",
    image=ecs.ContainerImage.from_asset(path.resolve(__dirname, "..", "eventhandler-image")),
    memory_limit_mi_b=256,
    logging=ecs.AwsLogDriver(stream_prefix="EventDemo", mode=ecs.AwsLogDriverMode.NON_BLOCKING)
)

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

# Pass an environment variable to the container 'TheContainer' in the task
rule.add_target(targets.EcsTask(
    cluster=cluster,
    task_definition=task_definition,
    task_count=1,
    container_overrides=[targets.ContainerOverride(
        container_name="TheContainer",
        environment=[targets.TaskEnvironmentVariable(
            name="I_WAS_TRIGGERED",
            value="From CloudWatch Events"
        )]
    )]
))
java
Cluster cluster;

// Create a Task Definition for the container to start
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromAsset(resolve(__dirname, "..", "eventhandler-image")))
        .memoryLimitMiB(256)
        .logging(AwsLogDriver.Builder.create().streamPrefix("EventDemo").mode(AwsLogDriverMode.NON_BLOCKING).build())
        .build());

// An Rule that describes the event trigger (in this case a scheduled run)
Rule rule = Rule.Builder.create(this, "Rule")
        .schedule(Schedule.expression("rate(1 minute)"))
        .build();

// Pass an environment variable to the container 'TheContainer' in the task
rule.addTarget(EcsTask.Builder.create()
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .taskCount(1)
        .containerOverrides(List.of(ContainerOverride.builder()
                .containerName("TheContainer")
                .environment(List.of(TaskEnvironmentVariable.builder()
                        .name("I_WAS_TRIGGERED")
                        .value("From CloudWatch Events")
                        .build()))
                .build()))
        .build());
csharp
Cluster cluster;

// Create a Task Definition for the container to start
var taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.AddContainer("TheContainer", new ContainerDefinitionOptions {
    Image = ContainerImage.FromAsset(Resolve(__dirname, "..", "eventhandler-image")),
    MemoryLimitMiB = 256,
    Logging = new AwsLogDriver(new AwsLogDriverProps { StreamPrefix = "EventDemo", Mode = AwsLogDriverMode.NON_BLOCKING })
});

// An Rule that describes the event trigger (in this case a scheduled run)
var rule = new Rule(this, "Rule", new RuleProps {
    Schedule = Schedule.Expression("rate(1 minute)")
});

// Pass an environment variable to the container 'TheContainer' in the task
rule.AddTarget(new EcsTask(new EcsTaskProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    TaskCount = 1,
    ContainerOverrides = new [] { new ContainerOverride {
        ContainerName = "TheContainer",
        Environment = new [] { new TaskEnvironmentVariable {
            Name = "I_WAS_TRIGGERED",
            Value = "From CloudWatch Events"
        } }
    } }
}));
go
var cluster Cluster

// Create a Task Definition for the container to start
taskDefinition := ecs.NewEc2TaskDefinition(this, jsii.String("TaskDef"))
taskDefinition.AddContainer(jsii.String("TheContainer"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromAsset(path.resolve(__dirname, jsii.String(".."), jsii.String("eventhandler-image"))),
	MemoryLimitMiB: jsii.Number(256),
	Logging: ecs.NewAwsLogDriver(&AwsLogDriverProps{
		StreamPrefix: jsii.String("EventDemo"),
		Mode: ecs.AwsLogDriverMode_NON_BLOCKING,
	}),
})

// An Rule that describes the event trigger (in this case a scheduled run)
rule := events.NewRule(this, jsii.String("Rule"), &RuleProps{
	Schedule: events.Schedule_Expression(jsii.String("rate(1 minute)")),
})

// Pass an environment variable to the container 'TheContainer' in the task
rule.AddTarget(targets.NewEcsTask(&EcsTaskProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	TaskCount: jsii.Number(1),
	ContainerOverrides: []ContainerOverride{
		&ContainerOverride{
			ContainerName: jsii.String("TheContainer"),
			Environment: []TaskEnvironmentVariable{
				&TaskEnvironmentVariable{
					Name: jsii.String("I_WAS_TRIGGERED"),
					Value: jsii.String("From CloudWatch Events"),
				},
			},
		},
	},
}))

Log Drivers ​

Currently Supported Log Drivers:

  • awslogs
  • fluentd
  • gelf
  • journald
  • json-file
  • splunk
  • syslog
  • awsfirelens
  • Generic
  • none

awslogs Log Driver ​

ts
// Create a Task Definition for the container to start
const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');
taskDefinition.addContainer('TheContainer', {
  image: ecs.ContainerImage.fromRegistry('example-image'),
  memoryLimitMiB: 256,
  logging: ecs.LogDrivers.awsLogs({
    streamPrefix: 'EventDemo',
    mode: ecs.AwsLogDriverMode.NON_BLOCKING,
    maxBufferSize: Size.mebibytes(25),
  }),
});
python
# Create a Task Definition for the container to start
task_definition = ecs.Ec2TaskDefinition(self, "TaskDef")
task_definition.add_container("TheContainer",
    image=ecs.ContainerImage.from_registry("example-image"),
    memory_limit_mi_b=256,
    logging=ecs.LogDrivers.aws_logs(
        stream_prefix="EventDemo",
        mode=ecs.AwsLogDriverMode.NON_BLOCKING,
        max_buffer_size=Size.mebibytes(25)
    )
)
java
// Create a Task Definition for the container to start
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("example-image"))
        .memoryLimitMiB(256)
        .logging(LogDrivers.awsLogs(AwsLogDriverProps.builder()
                .streamPrefix("EventDemo")
                .mode(AwsLogDriverMode.NON_BLOCKING)
                .maxBufferSize(Size.mebibytes(25))
                .build()))
        .build());
csharp
// Create a Task Definition for the container to start
var taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.AddContainer("TheContainer", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("example-image"),
    MemoryLimitMiB = 256,
    Logging = LogDrivers.AwsLogs(new AwsLogDriverProps {
        StreamPrefix = "EventDemo",
        Mode = AwsLogDriverMode.NON_BLOCKING,
        MaxBufferSize = Size.Mebibytes(25)
    })
});
go
// Create a Task Definition for the container to start
taskDefinition := ecs.NewEc2TaskDefinition(this, jsii.String("TaskDef"))
taskDefinition.AddContainer(jsii.String("TheContainer"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("example-image")),
	MemoryLimitMiB: jsii.Number(256),
	Logging: ecs.LogDrivers_AwsLogs(&AwsLogDriverProps{
		StreamPrefix: jsii.String("EventDemo"),
		Mode: ecs.AwsLogDriverMode_NON_BLOCKING,
		MaxBufferSize: awscdk.Size_Mebibytes(jsii.Number(25)),
	}),
})

fluentd Log Driver ​

ts
// Create a Task Definition for the container to start
const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');
taskDefinition.addContainer('TheContainer', {
  image: ecs.ContainerImage.fromRegistry('example-image'),
  memoryLimitMiB: 256,
  logging: ecs.LogDrivers.fluentd(),
});
python
# Create a Task Definition for the container to start
task_definition = ecs.Ec2TaskDefinition(self, "TaskDef")
task_definition.add_container("TheContainer",
    image=ecs.ContainerImage.from_registry("example-image"),
    memory_limit_mi_b=256,
    logging=ecs.LogDrivers.fluentd()
)
java
// Create a Task Definition for the container to start
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("example-image"))
        .memoryLimitMiB(256)
        .logging(LogDrivers.fluentd())
        .build());
csharp
// Create a Task Definition for the container to start
var taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.AddContainer("TheContainer", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("example-image"),
    MemoryLimitMiB = 256,
    Logging = LogDrivers.Fluentd()
});
go
// Create a Task Definition for the container to start
taskDefinition := ecs.NewEc2TaskDefinition(this, jsii.String("TaskDef"))
taskDefinition.AddContainer(jsii.String("TheContainer"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("example-image")),
	MemoryLimitMiB: jsii.Number(256),
	Logging: ecs.LogDrivers_Fluentd(),
})

gelf Log Driver ​

ts
// Create a Task Definition for the container to start
const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');
taskDefinition.addContainer('TheContainer', {
  image: ecs.ContainerImage.fromRegistry('example-image'),
  memoryLimitMiB: 256,
  logging: ecs.LogDrivers.gelf({ address: 'my-gelf-address' }),
});
python
# Create a Task Definition for the container to start
task_definition = ecs.Ec2TaskDefinition(self, "TaskDef")
task_definition.add_container("TheContainer",
    image=ecs.ContainerImage.from_registry("example-image"),
    memory_limit_mi_b=256,
    logging=ecs.LogDrivers.gelf(address="my-gelf-address")
)
java
// Create a Task Definition for the container to start
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("example-image"))
        .memoryLimitMiB(256)
        .logging(LogDrivers.gelf(GelfLogDriverProps.builder().address("my-gelf-address").build()))
        .build());
csharp
// Create a Task Definition for the container to start
var taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.AddContainer("TheContainer", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("example-image"),
    MemoryLimitMiB = 256,
    Logging = LogDrivers.Gelf(new GelfLogDriverProps { Address = "my-gelf-address" })
});
go
// Create a Task Definition for the container to start
taskDefinition := ecs.NewEc2TaskDefinition(this, jsii.String("TaskDef"))
taskDefinition.AddContainer(jsii.String("TheContainer"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("example-image")),
	MemoryLimitMiB: jsii.Number(256),
	Logging: ecs.LogDrivers_Gelf(&GelfLogDriverProps{
		Address: jsii.String("my-gelf-address"),
	}),
})

journald Log Driver ​

ts
// Create a Task Definition for the container to start
const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');
taskDefinition.addContainer('TheContainer', {
  image: ecs.ContainerImage.fromRegistry('example-image'),
  memoryLimitMiB: 256,
  logging: ecs.LogDrivers.journald(),
});
python
# Create a Task Definition for the container to start
task_definition = ecs.Ec2TaskDefinition(self, "TaskDef")
task_definition.add_container("TheContainer",
    image=ecs.ContainerImage.from_registry("example-image"),
    memory_limit_mi_b=256,
    logging=ecs.LogDrivers.journald()
)
java
// Create a Task Definition for the container to start
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("example-image"))
        .memoryLimitMiB(256)
        .logging(LogDrivers.journald())
        .build());
csharp
// Create a Task Definition for the container to start
var taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.AddContainer("TheContainer", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("example-image"),
    MemoryLimitMiB = 256,
    Logging = LogDrivers.Journald()
});
go
// Create a Task Definition for the container to start
taskDefinition := ecs.NewEc2TaskDefinition(this, jsii.String("TaskDef"))
taskDefinition.AddContainer(jsii.String("TheContainer"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("example-image")),
	MemoryLimitMiB: jsii.Number(256),
	Logging: ecs.LogDrivers_Journald(),
})

json-file Log Driver ​

ts
// Create a Task Definition for the container to start
const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');
taskDefinition.addContainer('TheContainer', {
  image: ecs.ContainerImage.fromRegistry('example-image'),
  memoryLimitMiB: 256,
  logging: ecs.LogDrivers.jsonFile(),
});
python
# Create a Task Definition for the container to start
task_definition = ecs.Ec2TaskDefinition(self, "TaskDef")
task_definition.add_container("TheContainer",
    image=ecs.ContainerImage.from_registry("example-image"),
    memory_limit_mi_b=256,
    logging=ecs.LogDrivers.json_file()
)
java
// Create a Task Definition for the container to start
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("example-image"))
        .memoryLimitMiB(256)
        .logging(LogDrivers.jsonFile())
        .build());
csharp
// Create a Task Definition for the container to start
var taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.AddContainer("TheContainer", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("example-image"),
    MemoryLimitMiB = 256,
    Logging = LogDrivers.JsonFile()
});
go
// Create a Task Definition for the container to start
taskDefinition := ecs.NewEc2TaskDefinition(this, jsii.String("TaskDef"))
taskDefinition.AddContainer(jsii.String("TheContainer"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("example-image")),
	MemoryLimitMiB: jsii.Number(256),
	Logging: ecs.LogDrivers_JsonFile(),
})

splunk Log Driver ​

ts
declare const secret: ecs.Secret;

// Create a Task Definition for the container to start
const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');
taskDefinition.addContainer('TheContainer', {
  image: ecs.ContainerImage.fromRegistry('example-image'),
  memoryLimitMiB: 256,
  logging: ecs.LogDrivers.splunk({
    secretToken: secret,
    url: 'my-splunk-url',
  }),
});
python
# secret: ecs.Secret


# Create a Task Definition for the container to start
task_definition = ecs.Ec2TaskDefinition(self, "TaskDef")
task_definition.add_container("TheContainer",
    image=ecs.ContainerImage.from_registry("example-image"),
    memory_limit_mi_b=256,
    logging=ecs.LogDrivers.splunk(
        secret_token=secret,
        url="my-splunk-url"
    )
)
java
Secret secret;


// Create a Task Definition for the container to start
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("example-image"))
        .memoryLimitMiB(256)
        .logging(LogDrivers.splunk(SplunkLogDriverProps.builder()
                .secretToken(secret)
                .url("my-splunk-url")
                .build()))
        .build());
csharp
Secret secret;


// Create a Task Definition for the container to start
var taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.AddContainer("TheContainer", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("example-image"),
    MemoryLimitMiB = 256,
    Logging = LogDrivers.Splunk(new SplunkLogDriverProps {
        SecretToken = secret,
        Url = "my-splunk-url"
    })
});
go
var secret Secret


// Create a Task Definition for the container to start
taskDefinition := ecs.NewEc2TaskDefinition(this, jsii.String("TaskDef"))
taskDefinition.AddContainer(jsii.String("TheContainer"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("example-image")),
	MemoryLimitMiB: jsii.Number(256),
	Logging: ecs.LogDrivers_Splunk(&SplunkLogDriverProps{
		SecretToken: secret,
		Url: jsii.String("my-splunk-url"),
	}),
})

syslog Log Driver ​

ts
// Create a Task Definition for the container to start
const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');
taskDefinition.addContainer('TheContainer', {
  image: ecs.ContainerImage.fromRegistry('example-image'),
  memoryLimitMiB: 256,
  logging: ecs.LogDrivers.syslog(),
});
python
# Create a Task Definition for the container to start
task_definition = ecs.Ec2TaskDefinition(self, "TaskDef")
task_definition.add_container("TheContainer",
    image=ecs.ContainerImage.from_registry("example-image"),
    memory_limit_mi_b=256,
    logging=ecs.LogDrivers.syslog()
)
java
// Create a Task Definition for the container to start
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("example-image"))
        .memoryLimitMiB(256)
        .logging(LogDrivers.syslog())
        .build());
csharp
// Create a Task Definition for the container to start
var taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.AddContainer("TheContainer", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("example-image"),
    MemoryLimitMiB = 256,
    Logging = LogDrivers.Syslog()
});
go
// Create a Task Definition for the container to start
taskDefinition := ecs.NewEc2TaskDefinition(this, jsii.String("TaskDef"))
taskDefinition.AddContainer(jsii.String("TheContainer"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("example-image")),
	MemoryLimitMiB: jsii.Number(256),
	Logging: ecs.LogDrivers_Syslog(),
})

firelens Log Driver ​

ts
// Create a Task Definition for the container to start
const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');
taskDefinition.addContainer('TheContainer', {
  image: ecs.ContainerImage.fromRegistry('example-image'),
  memoryLimitMiB: 256,
  logging: ecs.LogDrivers.firelens({
    options: {
        Name: 'firehose',
        region: 'us-west-2',
        delivery_stream: 'my-stream',
    },
  }),
});
python
# Create a Task Definition for the container to start
task_definition = ecs.Ec2TaskDefinition(self, "TaskDef")
task_definition.add_container("TheContainer",
    image=ecs.ContainerImage.from_registry("example-image"),
    memory_limit_mi_b=256,
    logging=ecs.LogDrivers.firelens(
        options={
            "Name": "firehose",
            "region": "us-west-2",
            "delivery_stream": "my-stream"
        }
    )
)
java
// Create a Task Definition for the container to start
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("example-image"))
        .memoryLimitMiB(256)
        .logging(LogDrivers.firelens(FireLensLogDriverProps.builder()
                .options(Map.of(
                        "Name", "firehose",
                        "region", "us-west-2",
                        "delivery_stream", "my-stream"))
                .build()))
        .build());
csharp
// Create a Task Definition for the container to start
var taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.AddContainer("TheContainer", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("example-image"),
    MemoryLimitMiB = 256,
    Logging = LogDrivers.Firelens(new FireLensLogDriverProps {
        Options = new Dictionary<string, string> {
            { "Name", "firehose" },
            { "region", "us-west-2" },
            { "delivery_stream", "my-stream" }
        }
    })
});
go
// Create a Task Definition for the container to start
taskDefinition := ecs.NewEc2TaskDefinition(this, jsii.String("TaskDef"))
taskDefinition.AddContainer(jsii.String("TheContainer"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("example-image")),
	MemoryLimitMiB: jsii.Number(256),
	Logging: ecs.LogDrivers_Firelens(&FireLensLogDriverProps{
		Options: map[string]*string{
			"Name": jsii.String("firehose"),
			"region": jsii.String("us-west-2"),
			"delivery_stream": jsii.String("my-stream"),
		},
	}),
})

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

ts
declare const secret: secretsmanager.Secret;
declare const parameter: ssm.StringParameter;

const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');
taskDefinition.addContainer('TheContainer', {
  image: ecs.ContainerImage.fromRegistry('example-image'),
  memoryLimitMiB: 256,
  logging: ecs.LogDrivers.firelens({
    options: {
      // ... log driver options here ...
    },
    secretOptions: { // Retrieved from AWS Secrets Manager or AWS Systems Manager Parameter Store
      apikey: ecs.Secret.fromSecretsManager(secret),
      host: ecs.Secret.fromSsmParameter(parameter),
    },
  }),
});
python
# secret: secretsmanager.Secret
# parameter: ssm.StringParameter


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


Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("example-image"))
        .memoryLimitMiB(256)
        .logging(LogDrivers.firelens(FireLensLogDriverProps.builder()
                .options(Map.of())
                .secretOptions(Map.of( // Retrieved from AWS Secrets Manager or AWS Systems Manager Parameter Store
                        "apikey", Secret.fromSecretsManager(secret),
                        "host", Secret.fromSsmParameter(parameter)))
                .build()))
        .build());
csharp
Secret secret;
StringParameter parameter;


var taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.AddContainer("TheContainer", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("example-image"),
    MemoryLimitMiB = 256,
    Logging = LogDrivers.Firelens(new FireLensLogDriverProps {
        Options = new Dictionary<string, object> { },
        SecretOptions = new Dictionary<string, Secret> {  // Retrieved from AWS Secrets Manager or AWS Systems Manager Parameter Store
            { "apikey", Secret.FromSecretsManager(secret) },
            { "host", Secret.FromSsmParameter(parameter) } }
    })
});
go
var secret Secret
var parameter StringParameter


taskDefinition := ecs.NewEc2TaskDefinition(this, jsii.String("TaskDef"))
taskDefinition.AddContainer(jsii.String("TheContainer"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("example-image")),
	MemoryLimitMiB: jsii.Number(256),
	Logging: ecs.LogDrivers_Firelens(&FireLensLogDriverProps{
		Options: map[string]interface{}{
		},
		SecretOptions: map[string]Secret{
			 // Retrieved from AWS Secrets Manager or AWS Systems Manager Parameter Store
			"apikey": ecs.Secret_fromSecretsManager(secret),
			"host": ecs.Secret_fromSsmParameter(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.

ts
const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');
taskDefinition.addContainer('TheContainer', {
  image: ecs.ContainerImage.fromRegistry('example-image'),
  memoryLimitMiB: 256,
  logging: 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',
    },
  }),
});
python
task_definition = ecs.Ec2TaskDefinition(self, "TaskDef")
task_definition.add_container("TheContainer",
    image=ecs.ContainerImage.from_registry("example-image"),
    memory_limit_mi_b=256,
    logging=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"
        }
    )
)
java
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("example-image"))
        .memoryLimitMiB(256)
        .logging(LogDrivers.firelens(FireLensLogDriverProps.builder()
                .options(Map.of(
                        "Name", "cloudwatch",
                        "region", "us-west-2",
                        "log_group_name", "firelens-fluent-bit",
                        "log_stream_prefix", "from-fluent-bit",
                        "auto_create_group", "true",
                        "log_retention_days", "1"))
                .build()))
        .build());
csharp
var taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.AddContainer("TheContainer", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("example-image"),
    MemoryLimitMiB = 256,
    Logging = LogDrivers.Firelens(new FireLensLogDriverProps {
        Options = new Dictionary<string, string> {
            { "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" }
        }
    })
});
go
taskDefinition := ecs.NewEc2TaskDefinition(this, jsii.String("TaskDef"))
taskDefinition.AddContainer(jsii.String("TheContainer"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("example-image")),
	MemoryLimitMiB: jsii.Number(256),
	Logging: ecs.LogDrivers_Firelens(&FireLensLogDriverProps{
		Options: map[string]*string{
			"Name": jsii.String("cloudwatch"),
			"region": jsii.String("us-west-2"),
			"log_group_name": jsii.String("firelens-fluent-bit"),
			"log_stream_prefix": jsii.String("from-fluent-bit"),
			"auto_create_group": jsii.String("true"),
			"log_retention_days": jsii.String("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.

ts
// Create a Task Definition for the container to start
const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');
taskDefinition.addContainer('TheContainer', {
  image: ecs.ContainerImage.fromRegistry('example-image'),
  memoryLimitMiB: 256,
  logging: new ecs.GenericLogDriver({
    logDriver: 'fluentd',
    options: {
      tag: 'example-tag',
    },
  }),
});
python
# Create a Task Definition for the container to start
task_definition = ecs.Ec2TaskDefinition(self, "TaskDef")
task_definition.add_container("TheContainer",
    image=ecs.ContainerImage.from_registry("example-image"),
    memory_limit_mi_b=256,
    logging=ecs.GenericLogDriver(
        log_driver="fluentd",
        options={
            "tag": "example-tag"
        }
    )
)
java
// Create a Task Definition for the container to start
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("example-image"))
        .memoryLimitMiB(256)
        .logging(GenericLogDriver.Builder.create()
                .logDriver("fluentd")
                .options(Map.of(
                        "tag", "example-tag"))
                .build())
        .build());
csharp
// Create a Task Definition for the container to start
var taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.AddContainer("TheContainer", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("example-image"),
    MemoryLimitMiB = 256,
    Logging = new GenericLogDriver(new GenericLogDriverProps {
        LogDriver = "fluentd",
        Options = new Dictionary<string, string> {
            { "tag", "example-tag" }
        }
    })
});
go
// Create a Task Definition for the container to start
taskDefinition := ecs.NewEc2TaskDefinition(this, jsii.String("TaskDef"))
taskDefinition.AddContainer(jsii.String("TheContainer"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("example-image")),
	MemoryLimitMiB: jsii.Number(256),
	Logging: ecs.NewGenericLogDriver(&GenericLogDriverProps{
		LogDriver: jsii.String("fluentd"),
		Options: map[string]*string{
			"tag": jsii.String("example-tag"),
		},
	}),
})

none Log Driver ​

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

ts
// Create a Task Definition for the container to start
const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');
taskDefinition.addContainer('TheContainer', {
  image: ecs.ContainerImage.fromRegistry('example-image'),
  memoryLimitMiB: 256,
  logging: ecs.LogDrivers.none(),
});
python
# Create a Task Definition for the container to start
task_definition = ecs.Ec2TaskDefinition(self, "TaskDef")
task_definition.add_container("TheContainer",
    image=ecs.ContainerImage.from_registry("example-image"),
    memory_limit_mi_b=256,
    logging=ecs.LogDrivers.none()
)
java
// Create a Task Definition for the container to start
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("example-image"))
        .memoryLimitMiB(256)
        .logging(LogDrivers.none())
        .build());
csharp
// Create a Task Definition for the container to start
var taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.AddContainer("TheContainer", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("example-image"),
    MemoryLimitMiB = 256,
    Logging = LogDrivers.None()
});
go
// Create a Task Definition for the container to start
taskDefinition := ecs.NewEc2TaskDefinition(this, jsii.String("TaskDef"))
taskDefinition.AddContainer(jsii.String("TheContainer"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("example-image")),
	MemoryLimitMiB: jsii.Number(256),
	Logging: ecs.LogDrivers_None(),
})

CloudMap Service Discovery ​

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

ts
declare const taskDefinition: ecs.TaskDefinition;
declare const cluster: ecs.Cluster;

const service = new ecs.Ec2Service(this, 'Service', {
  cluster,
  taskDefinition,
  cloudMapOptions: {
    // Create A records - useful for AWSVPC network mode.
    dnsRecordType: cloudmap.DnsRecordType.A,
  },
});
python
# task_definition: ecs.TaskDefinition
# cluster: ecs.Cluster


service = ecs.Ec2Service(self, "Service",
    cluster=cluster,
    task_definition=task_definition,
    cloud_map_options=ecs.CloudMapOptions(
        # Create A records - useful for AWSVPC network mode.
        dns_record_type=cloudmap.DnsRecordType.A
    )
)
java
TaskDefinition taskDefinition;
Cluster cluster;


Ec2Service service = Ec2Service.Builder.create(this, "Service")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .cloudMapOptions(CloudMapOptions.builder()
                // Create A records - useful for AWSVPC network mode.
                .dnsRecordType(DnsRecordType.A)
                .build())
        .build();
csharp
TaskDefinition taskDefinition;
Cluster cluster;


var service = new Ec2Service(this, "Service", new Ec2ServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    CloudMapOptions = new CloudMapOptions {
        // Create A records - useful for AWSVPC network mode.
        DnsRecordType = DnsRecordType.A
    }
});
go
var taskDefinition TaskDefinition
var cluster Cluster


service := ecs.NewEc2Service(this, jsii.String("Service"), &Ec2ServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	CloudMapOptions: &CloudMapOptions{
		// Create A records - useful for AWSVPC network mode.
		DnsRecordType: cloudmap.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:

ts
declare const taskDefinition: ecs.TaskDefinition;
declare const cluster: ecs.Cluster;

// Add a container to the task definition
const specificContainer = taskDefinition.addContainer('Container', {
  image: ecs.ContainerImage.fromRegistry('/aws/aws-example-app'),
  memoryLimitMiB: 2048,
});

// Add a port mapping
specificContainer.addPortMappings({
  containerPort: 7600,
  protocol: ecs.Protocol.TCP,
});

new ecs.Ec2Service(this, 'Service', {
  cluster,
  taskDefinition,
  minHealthyPercent: 100,
  cloudMapOptions: {
    // Create SRV records - useful for bridge networking
    dnsRecordType: cloudmap.DnsRecordType.SRV,
    // Targets port TCP port 7600 `specificContainer`
    container: specificContainer,
    containerPort: 7600,
  },
});
python
# task_definition: ecs.TaskDefinition
# cluster: ecs.Cluster


# Add a container to the task definition
specific_container = task_definition.add_container("Container",
    image=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=ecs.Protocol.TCP
)

ecs.Ec2Service(self, "Service",
    cluster=cluster,
    task_definition=task_definition,
    min_healthy_percent=100,
    cloud_map_options=ecs.CloudMapOptions(
        # Create SRV records - useful for bridge networking
        dns_record_type=cloudmap.DnsRecordType.SRV,
        # Targets port TCP port 7600 `specificContainer`
        container=specific_container,
        container_port=7600
    )
)
java
TaskDefinition taskDefinition;
Cluster cluster;


// Add a container to the task definition
ContainerDefinition specificContainer = taskDefinition.addContainer("Container", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("/aws/aws-example-app"))
        .memoryLimitMiB(2048)
        .build());

// Add a port mapping
specificContainer.addPortMappings(PortMapping.builder()
        .containerPort(7600)
        .protocol(Protocol.TCP)
        .build());

Ec2Service.Builder.create(this, "Service")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .minHealthyPercent(100)
        .cloudMapOptions(CloudMapOptions.builder()
                // Create SRV records - useful for bridge networking
                .dnsRecordType(DnsRecordType.SRV)
                // Targets port TCP port 7600 `specificContainer`
                .container(specificContainer)
                .containerPort(7600)
                .build())
        .build();
csharp
TaskDefinition taskDefinition;
Cluster cluster;


// Add a container to the task definition
var specificContainer = taskDefinition.AddContainer("Container", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("/aws/aws-example-app"),
    MemoryLimitMiB = 2048
});

// Add a port mapping
specificContainer.AddPortMappings(new PortMapping {
    ContainerPort = 7600,
    Protocol = Protocol.TCP
});

new Ec2Service(this, "Service", new Ec2ServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    MinHealthyPercent = 100,
    CloudMapOptions = new CloudMapOptions {
        // Create SRV records - useful for bridge networking
        DnsRecordType = DnsRecordType.SRV,
        // Targets port TCP port 7600 `specificContainer`
        Container = specificContainer,
        ContainerPort = 7600
    }
});
go
var taskDefinition TaskDefinition
var cluster Cluster


// Add a container to the task definition
specificContainer := taskDefinition.AddContainer(jsii.String("Container"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("/aws/aws-example-app")),
	MemoryLimitMiB: jsii.Number(2048),
})

// Add a port mapping
specificContainer.AddPortMappings(&PortMapping{
	ContainerPort: jsii.Number(7600),
	Protocol: ecs.Protocol_TCP,
})

ecs.NewEc2Service(this, jsii.String("Service"), &Ec2ServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	MinHealthyPercent: jsii.Number(100),
	CloudMapOptions: &CloudMapOptions{
		// Create SRV records - useful for bridge networking
		DnsRecordType: cloudmap.DnsRecordType_SRV,
		// Targets port TCP port 7600 `specificContainer`
		Container: specificContainer,
		ContainerPort: jsii.Number(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 associateCloudMapService method:

ts
declare const cloudMapService: cloudmap.Service;
declare const ecsService: ecs.FargateService;

ecsService.associateCloudMapService({
  service: cloudMapService,
});
python
# cloud_map_service: cloudmap.Service
# ecs_service: ecs.FargateService


ecs_service.associate_cloud_map_service(
    service=cloud_map_service
)
java
Service cloudMapService;
FargateService ecsService;


ecsService.associateCloudMapService(AssociateCloudMapServiceOptions.builder()
        .service(cloudMapService)
        .build());
csharp
Service cloudMapService;
FargateService ecsService;


ecsService.AssociateCloudMapService(new AssociateCloudMapServiceOptions {
    Service = cloudMapService
});
go
var cloudMapService Service
var ecsService FargateService


ecsService.AssociateCloudMapService(&AssociateCloudMapServiceOptions{
	Service: cloudMapService,
})

Using an Existing Cloud Map Namespace ​

You can use an existing Cloud Map namespace as the default namespace for a cluster instead of creating a new one. This is useful when you want to share a namespace across multiple clusters or when you want to use a namespace that was created outside of CDK:

ts
declare const vpc: ec2.Vpc;

// Create or reference an existing namespace
const existingNamespace = new cloudmap.PrivateDnsNamespace(this, 'Namespace', {
  name: 'example.local',
  vpc,
});

const cluster = new ecs.Cluster(this, 'Cluster', { vpc });

// Use the existing namespace as the default
cluster.addExistingDefaultCloudMapNamespace({
  namespace: existingNamespace,
  useForServiceConnect: true,
});
python
# vpc: ec2.Vpc


# Create or reference an existing namespace
existing_namespace = cloudmap.PrivateDnsNamespace(self, "Namespace",
    name="example.local",
    vpc=vpc
)

cluster = ecs.Cluster(self, "Cluster", vpc=vpc)

# Use the existing namespace as the default
cluster.add_existing_default_cloud_map_namespace(
    namespace=existing_namespace,
    use_for_service_connect=True
)
java
Vpc vpc;


// Create or reference an existing namespace
PrivateDnsNamespace existingNamespace = PrivateDnsNamespace.Builder.create(this, "Namespace")
        .name("example.local")
        .vpc(vpc)
        .build();

Cluster cluster = Cluster.Builder.create(this, "Cluster").vpc(vpc).build();

// Use the existing namespace as the default
cluster.addExistingDefaultCloudMapNamespace(ExistingCloudMapNamespaceOptions.builder()
        .namespace(existingNamespace)
        .useForServiceConnect(true)
        .build());
csharp
Vpc vpc;


// Create or reference an existing namespace
var existingNamespace = new PrivateDnsNamespace(this, "Namespace", new PrivateDnsNamespaceProps {
    Name = "example.local",
    Vpc = vpc
});

var cluster = new Cluster(this, "Cluster", new ClusterProps { Vpc = vpc });

// Use the existing namespace as the default
cluster.AddExistingDefaultCloudMapNamespace(new ExistingCloudMapNamespaceOptions {
    Namespace = existingNamespace,
    UseForServiceConnect = true
});
go
var vpc Vpc


// Create or reference an existing namespace
existingNamespace := cloudmap.NewPrivateDnsNamespace(this, jsii.String("Namespace"), &PrivateDnsNamespaceProps{
	Name: jsii.String("example.local"),
	Vpc: Vpc,
})

cluster := ecs.NewCluster(this, jsii.String("Cluster"), &ClusterProps{
	Vpc: Vpc,
})

// Use the existing namespace as the default
cluster.AddExistingDefaultCloudMapNamespace(&ExistingCloudMapNamespaceOptions{
	Namespace: existingNamespace,
	UseForServiceConnect: jsii.Boolean(true),
})

You can also import an existing namespace:

ts
declare const vpc: ec2.Vpc;

const importedNamespace = cloudmap.PrivateDnsNamespace.fromPrivateDnsNamespaceAttributes(
  this, 'ImportedNamespace', {
    namespaceId: 'ns-xxxxxxxxxxxxx',
    namespaceArn: 'arn:aws:servicediscovery:us-east-1:123456789012:namespace/ns-xxxxxxxxxxxxx',
    namespaceName: 'example.local',
  }
);

const cluster = new ecs.Cluster(this, 'Cluster', { vpc });

cluster.addExistingDefaultCloudMapNamespace({
  namespace: importedNamespace,
});
python
# vpc: ec2.Vpc


imported_namespace = cloudmap.PrivateDnsNamespace.from_private_dns_namespace_attributes(self, "ImportedNamespace",
    namespace_id="ns-xxxxxxxxxxxxx",
    namespace_arn="arn:aws:servicediscovery:us-east-1:123456789012:namespace/ns-xxxxxxxxxxxxx",
    namespace_name="example.local"
)

cluster = ecs.Cluster(self, "Cluster", vpc=vpc)

cluster.add_existing_default_cloud_map_namespace(
    namespace=imported_namespace
)
java
Vpc vpc;


IPrivateDnsNamespace importedNamespace = PrivateDnsNamespace.fromPrivateDnsNamespaceAttributes(this, "ImportedNamespace", PrivateDnsNamespaceAttributes.builder()
        .namespaceId("ns-xxxxxxxxxxxxx")
        .namespaceArn("arn:aws:servicediscovery:us-east-1:123456789012:namespace/ns-xxxxxxxxxxxxx")
        .namespaceName("example.local")
        .build());

Cluster cluster = Cluster.Builder.create(this, "Cluster").vpc(vpc).build();

cluster.addExistingDefaultCloudMapNamespace(ExistingCloudMapNamespaceOptions.builder()
        .namespace(importedNamespace)
        .build());
csharp
Vpc vpc;


var importedNamespace = PrivateDnsNamespace.FromPrivateDnsNamespaceAttributes(this, "ImportedNamespace", new PrivateDnsNamespaceAttributes {
    NamespaceId = "ns-xxxxxxxxxxxxx",
    NamespaceArn = "arn:aws:servicediscovery:us-east-1:123456789012:namespace/ns-xxxxxxxxxxxxx",
    NamespaceName = "example.local"
});

var cluster = new Cluster(this, "Cluster", new ClusterProps { Vpc = vpc });

cluster.AddExistingDefaultCloudMapNamespace(new ExistingCloudMapNamespaceOptions {
    Namespace = importedNamespace
});
go
var vpc Vpc


importedNamespace := cloudmap.PrivateDnsNamespace_FromPrivateDnsNamespaceAttributes(this, jsii.String("ImportedNamespace"), &PrivateDnsNamespaceAttributes{
	NamespaceId: jsii.String("ns-xxxxxxxxxxxxx"),
	NamespaceArn: jsii.String("arn:aws:servicediscovery:us-east-1:123456789012:namespace/ns-xxxxxxxxxxxxx"),
	NamespaceName: jsii.String("example.local"),
})

cluster := ecs.NewCluster(this, jsii.String("Cluster"), &ClusterProps{
	Vpc: Vpc,
})

cluster.AddExistingDefaultCloudMapNamespace(&ExistingCloudMapNamespaceOptions{
	Namespace: importedNamespace,
})

Capacity Providers ​

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

Fargate Capacity Providers ​

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

ts
declare const vpc: ec2.Vpc;

const cluster = new ecs.Cluster(this, 'FargateCPCluster', {
  vpc,
  enableFargateCapacityProviders: true,
});

const taskDefinition = new ecs.FargateTaskDefinition(this, 'TaskDef');

taskDefinition.addContainer('web', {
  image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
});

new ecs.FargateService(this, 'FargateService', {
  cluster,
  taskDefinition,
  minHealthyPercent: 100,
  capacityProviderStrategies: [
    {
      capacityProvider: 'FARGATE_SPOT',
      weight: 2,
    },
    {
      capacityProvider: 'FARGATE',
      weight: 1,
    },
  ],
});
python
# vpc: ec2.Vpc


cluster = ecs.Cluster(self, "FargateCPCluster",
    vpc=vpc,
    enable_fargate_capacity_providers=True
)

task_definition = ecs.FargateTaskDefinition(self, "TaskDef")

task_definition.add_container("web",
    image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample")
)

ecs.FargateService(self, "FargateService",
    cluster=cluster,
    task_definition=task_definition,
    min_healthy_percent=100,
    capacity_provider_strategies=[ecs.CapacityProviderStrategy(
        capacity_provider="FARGATE_SPOT",
        weight=2
    ), ecs.CapacityProviderStrategy(
        capacity_provider="FARGATE",
        weight=1
    )
    ]
)
java
Vpc vpc;


Cluster cluster = Cluster.Builder.create(this, "FargateCPCluster")
        .vpc(vpc)
        .enableFargateCapacityProviders(true)
        .build();

FargateTaskDefinition taskDefinition = new FargateTaskDefinition(this, "TaskDef");

taskDefinition.addContainer("web", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
        .build());

FargateService.Builder.create(this, "FargateService")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .minHealthyPercent(100)
        .capacityProviderStrategies(List.of(CapacityProviderStrategy.builder()
                .capacityProvider("FARGATE_SPOT")
                .weight(2)
                .build(), CapacityProviderStrategy.builder()
                .capacityProvider("FARGATE")
                .weight(1)
                .build()))
        .build();
csharp
Vpc vpc;


var cluster = new Cluster(this, "FargateCPCluster", new ClusterProps {
    Vpc = vpc,
    EnableFargateCapacityProviders = true
});

var taskDefinition = new FargateTaskDefinition(this, "TaskDef");

taskDefinition.AddContainer("web", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
});

new FargateService(this, "FargateService", new FargateServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    MinHealthyPercent = 100,
    CapacityProviderStrategies = new [] { new CapacityProviderStrategy {
        CapacityProvider = "FARGATE_SPOT",
        Weight = 2
    }, new CapacityProviderStrategy {
        CapacityProvider = "FARGATE",
        Weight = 1
    } }
});
go
var vpc Vpc


cluster := ecs.NewCluster(this, jsii.String("FargateCPCluster"), &ClusterProps{
	Vpc: Vpc,
	EnableFargateCapacityProviders: jsii.Boolean(true),
})

taskDefinition := ecs.NewFargateTaskDefinition(this, jsii.String("TaskDef"))

taskDefinition.AddContainer(jsii.String("web"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
})

ecs.NewFargateService(this, jsii.String("FargateService"), &FargateServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	MinHealthyPercent: jsii.Number(100),
	CapacityProviderStrategies: []CapacityProviderStrategy{
		&CapacityProviderStrategy{
			CapacityProvider: jsii.String("FARGATE_SPOT"),
			Weight: jsii.Number(2),
		},
		&CapacityProviderStrategy{
			CapacityProvider: jsii.String("FARGATE"),
			Weight: jsii.Number(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 enableManagedScaling to false.

Additionally Managed Termination Protection is enabled by default to prevent scale-in behavior from terminating instances that have non-daemon tasks running on them. This is ideal for tasks that can be run to completion. If your tasks are safe to interrupt then this protection can be disabled by setting enableManagedTerminationProtection to false. Managed Scaling must be enabled for Managed Termination Protection to work.

Currently there is a known CloudFormation issue that prevents CloudFormation from automatically deleting Auto Scaling Groups that have Managed Termination Protection enabled. To work around this issue you could set enableManagedTerminationProtection 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 performed without disruptions to workloads. When enableManagedDraining is not specified (recommended), CloudFormation will implicitly enable managed draining. Set it to true for explicit enablement or false to disable.

ts
declare const vpc: ec2.Vpc;

const cluster = new ecs.Cluster(this, 'Cluster', {
  vpc,
});

const autoScalingGroup = new autoscaling.AutoScalingGroup(this, 'ASG', {
  vpc,
  instanceType: new ec2.InstanceType('t2.micro'),
  machineImage: ecs.EcsOptimizedImage.amazonLinux2(),
  minCapacity: 0,
  maxCapacity: 100,
});

const capacityProvider = new ecs.AsgCapacityProvider(this, 'AsgCapacityProvider', {
  autoScalingGroup,
  instanceWarmupPeriod: 300,
});
cluster.addAsgCapacityProvider(capacityProvider);

const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');

taskDefinition.addContainer('web', {
  image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
  memoryReservationMiB: 256,
});

new ecs.Ec2Service(this, 'EC2Service', {
  cluster,
  taskDefinition,
  minHealthyPercent: 100,
  capacityProviderStrategies: [
    {
      capacityProvider: capacityProvider.capacityProviderName,
      weight: 1,
    },
  ],
});
python
# vpc: ec2.Vpc


cluster = ecs.Cluster(self, "Cluster",
    vpc=vpc
)

auto_scaling_group = autoscaling.AutoScalingGroup(self, "ASG",
    vpc=vpc,
    instance_type=ec2.InstanceType("t2.micro"),
    machine_image=ecs.EcsOptimizedImage.amazon_linux2(),
    min_capacity=0,
    max_capacity=100
)

capacity_provider = ecs.AsgCapacityProvider(self, "AsgCapacityProvider",
    auto_scaling_group=auto_scaling_group,
    instance_warmup_period=300
)
cluster.add_asg_capacity_provider(capacity_provider)

task_definition = ecs.Ec2TaskDefinition(self, "TaskDef")

task_definition.add_container("web",
    image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample"),
    memory_reservation_mi_b=256
)

ecs.Ec2Service(self, "EC2Service",
    cluster=cluster,
    task_definition=task_definition,
    min_healthy_percent=100,
    capacity_provider_strategies=[ecs.CapacityProviderStrategy(
        capacity_provider=capacity_provider.capacity_provider_name,
        weight=1
    )
    ]
)
java
Vpc vpc;


Cluster cluster = Cluster.Builder.create(this, "Cluster")
        .vpc(vpc)
        .build();

AutoScalingGroup autoScalingGroup = AutoScalingGroup.Builder.create(this, "ASG")
        .vpc(vpc)
        .instanceType(new InstanceType("t2.micro"))
        .machineImage(EcsOptimizedImage.amazonLinux2())
        .minCapacity(0)
        .maxCapacity(100)
        .build();

AsgCapacityProvider capacityProvider = AsgCapacityProvider.Builder.create(this, "AsgCapacityProvider")
        .autoScalingGroup(autoScalingGroup)
        .instanceWarmupPeriod(300)
        .build();
cluster.addAsgCapacityProvider(capacityProvider);

Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");

taskDefinition.addContainer("web", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
        .memoryReservationMiB(256)
        .build());

Ec2Service.Builder.create(this, "EC2Service")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .minHealthyPercent(100)
        .capacityProviderStrategies(List.of(CapacityProviderStrategy.builder()
                .capacityProvider(capacityProvider.getCapacityProviderName())
                .weight(1)
                .build()))
        .build();
csharp
Vpc vpc;


var cluster = new Cluster(this, "Cluster", new ClusterProps {
    Vpc = vpc
});

var autoScalingGroup = new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
    Vpc = vpc,
    InstanceType = new InstanceType("t2.micro"),
    MachineImage = EcsOptimizedImage.AmazonLinux2(),
    MinCapacity = 0,
    MaxCapacity = 100
});

var capacityProvider = new AsgCapacityProvider(this, "AsgCapacityProvider", new AsgCapacityProviderProps {
    AutoScalingGroup = autoScalingGroup,
    InstanceWarmupPeriod = 300
});
cluster.AddAsgCapacityProvider(capacityProvider);

var taskDefinition = new Ec2TaskDefinition(this, "TaskDef");

taskDefinition.AddContainer("web", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
    MemoryReservationMiB = 256
});

new Ec2Service(this, "EC2Service", new Ec2ServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    MinHealthyPercent = 100,
    CapacityProviderStrategies = new [] { new CapacityProviderStrategy {
        CapacityProvider = capacityProvider.CapacityProviderName,
        Weight = 1
    } }
});
go
var vpc Vpc


cluster := ecs.NewCluster(this, jsii.String("Cluster"), &ClusterProps{
	Vpc: Vpc,
})

autoScalingGroup := autoscaling.NewAutoScalingGroup(this, jsii.String("ASG"), &AutoScalingGroupProps{
	Vpc: Vpc,
	InstanceType: ec2.NewInstanceType(jsii.String("t2.micro")),
	MachineImage: ecs.EcsOptimizedImage_AmazonLinux2(),
	MinCapacity: jsii.Number(0),
	MaxCapacity: jsii.Number(100),
})

capacityProvider := ecs.NewAsgCapacityProvider(this, jsii.String("AsgCapacityProvider"), &AsgCapacityProviderProps{
	AutoScalingGroup: AutoScalingGroup,
	InstanceWarmupPeriod: jsii.Number(300),
})
cluster.AddAsgCapacityProvider(capacityProvider)

taskDefinition := ecs.NewEc2TaskDefinition(this, jsii.String("TaskDef"))

taskDefinition.AddContainer(jsii.String("web"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	MemoryReservationMiB: jsii.Number(256),
})

ecs.NewEc2Service(this, jsii.String("EC2Service"), &Ec2ServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	MinHealthyPercent: jsii.Number(100),
	CapacityProviderStrategies: []CapacityProviderStrategy{
		&CapacityProviderStrategy{
			CapacityProvider: capacityProvider.CapacityProviderName,
			Weight: jsii.Number(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

ts
declare const vpc: ec2.Vpc;

const cluster = new ecs.Cluster(this, 'Cluster', { vpc });

const securityGroup = new ec2.SecurityGroup(this, 'SecurityGroup', {
  vpc,
  description: 'Security group for managed instances',
});

const miCapacityProvider = new ecs.ManagedInstancesCapacityProvider(this, 'MICapacityProvider', {
  capacityOptionType: ecs.CapacityOptionType.SPOT,
  subnets: vpc.privateSubnets,
  securityGroups: [securityGroup],
  instanceRequirements: {
    vCpuCountMin: 1,
    memoryMin: Size.gibibytes(2),
  },
});

// Optionally configure security group rules using IConnectable interface
miCapacityProvider.connections.allowFrom(ec2.Peer.ipv4(vpc.vpcCidrBlock), ec2.Port.tcp(80));

// Add the capacity provider to the cluster
cluster.addManagedInstancesCapacityProvider(miCapacityProvider);

const taskDefinition = new ecs.TaskDefinition(this, 'TaskDef', {
  memoryMiB: '512',
  cpu: '256',
  networkMode: ecs.NetworkMode.AWS_VPC,
  compatibility: ecs.Compatibility.MANAGED_INSTANCES,
});

taskDefinition.addContainer('web', {
  image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
  memoryReservationMiB: 256,
});

new ecs.FargateService(this, 'FargateService', {
  cluster,
  taskDefinition,
  minHealthyPercent: 100,
  capacityProviderStrategies: [
    {
      capacityProvider: miCapacityProvider.capacityProviderName,
      weight: 1,
    },
  ],
});
python
# vpc: ec2.Vpc


cluster = ecs.Cluster(self, "Cluster", vpc=vpc)

security_group = ec2.SecurityGroup(self, "SecurityGroup",
    vpc=vpc,
    description="Security group for managed instances"
)

mi_capacity_provider = ecs.ManagedInstancesCapacityProvider(self, "MICapacityProvider",
    capacity_option_type=ecs.CapacityOptionType.SPOT,
    subnets=vpc.private_subnets,
    security_groups=[security_group],
    instance_requirements=ec2.InstanceRequirementsConfig(
        v_cpu_count_min=1,
        memory_min=Size.gibibytes(2)
    )
)

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

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

task_definition = ecs.TaskDefinition(self, "TaskDef",
    memory_mi_b="512",
    cpu="256",
    network_mode=ecs.NetworkMode.AWS_VPC,
    compatibility=ecs.Compatibility.MANAGED_INSTANCES
)

task_definition.add_container("web",
    image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample"),
    memory_reservation_mi_b=256
)

ecs.FargateService(self, "FargateService",
    cluster=cluster,
    task_definition=task_definition,
    min_healthy_percent=100,
    capacity_provider_strategies=[ecs.CapacityProviderStrategy(
        capacity_provider=mi_capacity_provider.capacity_provider_name,
        weight=1
    )
    ]
)
java
Vpc vpc;


Cluster cluster = Cluster.Builder.create(this, "Cluster").vpc(vpc).build();

SecurityGroup securityGroup = SecurityGroup.Builder.create(this, "SecurityGroup")
        .vpc(vpc)
        .description("Security group for managed instances")
        .build();

ManagedInstancesCapacityProvider miCapacityProvider = ManagedInstancesCapacityProvider.Builder.create(this, "MICapacityProvider")
        .capacityOptionType(CapacityOptionType.SPOT)
        .subnets(vpc.getPrivateSubnets())
        .securityGroups(List.of(securityGroup))
        .instanceRequirements(InstanceRequirementsConfig.builder()
                .vCpuCountMin(1)
                .memoryMin(Size.gibibytes(2))
                .build())
        .build();

// Optionally configure security group rules using IConnectable interface
miCapacityProvider.connections.allowFrom(Peer.ipv4(vpc.getVpcCidrBlock()), Port.tcp(80));

// Add the capacity provider to the cluster
cluster.addManagedInstancesCapacityProvider(miCapacityProvider);

TaskDefinition taskDefinition = TaskDefinition.Builder.create(this, "TaskDef")
        .memoryMiB("512")
        .cpu("256")
        .networkMode(NetworkMode.AWS_VPC)
        .compatibility(Compatibility.MANAGED_INSTANCES)
        .build();

taskDefinition.addContainer("web", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
        .memoryReservationMiB(256)
        .build());

FargateService.Builder.create(this, "FargateService")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .minHealthyPercent(100)
        .capacityProviderStrategies(List.of(CapacityProviderStrategy.builder()
                .capacityProvider(miCapacityProvider.getCapacityProviderName())
                .weight(1)
                .build()))
        .build();
csharp
Vpc vpc;


var cluster = new Cluster(this, "Cluster", new ClusterProps { Vpc = vpc });

var securityGroup = new SecurityGroup(this, "SecurityGroup", new SecurityGroupProps {
    Vpc = vpc,
    Description = "Security group for managed instances"
});

var miCapacityProvider = new ManagedInstancesCapacityProvider(this, "MICapacityProvider", new ManagedInstancesCapacityProviderProps {
    CapacityOptionType = CapacityOptionType.SPOT,
    Subnets = vpc.PrivateSubnets,
    SecurityGroups = new [] { securityGroup },
    InstanceRequirements = new InstanceRequirementsConfig {
        VCpuCountMin = 1,
        MemoryMin = Size.Gibibytes(2)
    }
});

// Optionally configure security group rules using IConnectable interface
miCapacityProvider.Connections.AllowFrom(Peer.Ipv4(vpc.VpcCidrBlock), Port.Tcp(80));

// Add the capacity provider to the cluster
cluster.AddManagedInstancesCapacityProvider(miCapacityProvider);

var taskDefinition = new TaskDefinition(this, "TaskDef", new TaskDefinitionProps {
    MemoryMiB = "512",
    Cpu = "256",
    NetworkMode = NetworkMode.AWS_VPC,
    Compatibility = Compatibility.MANAGED_INSTANCES
});

taskDefinition.AddContainer("web", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
    MemoryReservationMiB = 256
});

new FargateService(this, "FargateService", new FargateServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    MinHealthyPercent = 100,
    CapacityProviderStrategies = new [] { new CapacityProviderStrategy {
        CapacityProvider = miCapacityProvider.CapacityProviderName,
        Weight = 1
    } }
});
go
var vpc Vpc


cluster := ecs.NewCluster(this, jsii.String("Cluster"), &ClusterProps{
	Vpc: Vpc,
})

securityGroup := ec2.NewSecurityGroup(this, jsii.String("SecurityGroup"), &SecurityGroupProps{
	Vpc: Vpc,
	Description: jsii.String("Security group for managed instances"),
})

miCapacityProvider := ecs.NewManagedInstancesCapacityProvider(this, jsii.String("MICapacityProvider"), &ManagedInstancesCapacityProviderProps{
	CapacityOptionType: ecs.CapacityOptionType_SPOT,
	Subnets: vpc.PrivateSubnets,
	SecurityGroups: []ISecurityGroup{
		securityGroup,
	},
	InstanceRequirements: &InstanceRequirementsConfig{
		VCpuCountMin: jsii.Number(1),
		MemoryMin: awscdk.Size_Gibibytes(jsii.Number(2)),
	},
})

// Optionally configure security group rules using IConnectable interface
miCapacityProvider.Connections.AllowFrom(ec2.Peer_Ipv4(vpc.VpcCidrBlock), ec2.Port_Tcp(jsii.Number(80)))

// Add the capacity provider to the cluster
cluster.AddManagedInstancesCapacityProvider(miCapacityProvider)

taskDefinition := ecs.NewTaskDefinition(this, jsii.String("TaskDef"), &TaskDefinitionProps{
	MemoryMiB: jsii.String("512"),
	Cpu: jsii.String("256"),
	NetworkMode: ecs.NetworkMode_AWS_VPC,
	Compatibility: ecs.Compatibility_MANAGED_INSTANCES,
})

taskDefinition.AddContainer(jsii.String("web"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	MemoryReservationMiB: jsii.Number(256),
})

ecs.NewFargateService(this, jsii.String("FargateService"), &FargateServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	MinHealthyPercent: jsii.Number(100),
	CapacityProviderStrategies: []CapacityProviderStrategy{
		&CapacityProviderStrategy{
			CapacityProvider: miCapacityProvider.CapacityProviderName,
			Weight: jsii.Number(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.

ts
declare const vpc: ec2.Vpc;

const cluster = new ecs.Cluster(this, 'Cluster', { vpc });

// Add your custom policies to the role.
const customInstanceRole = new iam.Role(this, 'CustomInstanceRole', {
  assumedBy: new iam.ServicePrincipal('ec2.amazonaws.com'),
});

const customInstanceProfile = new iam.InstanceProfile(this, 'CustomInstanceProfile', {
  role: customInstanceRole,
});

// Add your custom policies to the role.
const customInfrastructureRole = new iam.Role(this, 'CustomInfrastructureRole', {
  assumedBy: new iam.ServicePrincipal('ecs.amazonaws.com'),
});

// Add PassRole permission to allow ECS to pass the instance role to EC2.
customInfrastructureRole.addToPolicy(new iam.PolicyStatement({
  effect: iam.Effect.ALLOW,
  actions: ['iam:PassRole'],
  resources: [customInstanceRole.roleArn],
  conditions: {
    StringEquals: {
      'iam:PassedToService': 'ec2.amazonaws.com',
    },
  },
}));

const securityGroup = new ec2.SecurityGroup(this, 'SecurityGroup', {
  vpc,
  description: 'Security group for managed instances',
});

const miCapacityProviderCustom = new ecs.ManagedInstancesCapacityProvider(this, 'MICapacityProviderCustomRoles', {
  infrastructureRole: customInfrastructureRole,
  ec2InstanceProfile: customInstanceProfile,
  subnets: vpc.privateSubnets,
  securityGroups: [securityGroup],
});

// Add the capacity provider to the cluster
cluster.addManagedInstancesCapacityProvider(miCapacityProviderCustom);

const taskDefinition = new ecs.TaskDefinition(this, 'TaskDef', {
  memoryMiB: '512',
  cpu: '256',
  networkMode: ecs.NetworkMode.AWS_VPC,
  compatibility: ecs.Compatibility.MANAGED_INSTANCES,
});

taskDefinition.addContainer('web', {
  image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
  memoryReservationMiB: 256,
});


new ecs.FargateService(this, 'FargateService', {

  cluster,
  taskDefinition,
  minHealthyPercent: 100,
  capacityProviderStrategies: [
    {
      capacityProvider: miCapacityProviderCustom.capacityProviderName,
      weight: 1,
    },
  ],
});
python
# vpc: ec2.Vpc


cluster = ecs.Cluster(self, "Cluster", vpc=vpc)

# Add your custom policies to the role.
custom_instance_role = iam.Role(self, "CustomInstanceRole",
    assumed_by=iam.ServicePrincipal("ec2.amazonaws.com")
)

custom_instance_profile = iam.InstanceProfile(self, "CustomInstanceProfile",
    role=custom_instance_role
)

# Add your custom policies to the role.
custom_infrastructure_role = iam.Role(self, "CustomInfrastructureRole",
    assumed_by=iam.ServicePrincipal("ecs.amazonaws.com")
)

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

security_group = ec2.SecurityGroup(self, "SecurityGroup",
    vpc=vpc,
    description="Security group for managed instances"
)

mi_capacity_provider_custom = ecs.ManagedInstancesCapacityProvider(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 = ecs.TaskDefinition(self, "TaskDef",
    memory_mi_b="512",
    cpu="256",
    network_mode=ecs.NetworkMode.AWS_VPC,
    compatibility=ecs.Compatibility.MANAGED_INSTANCES
)

task_definition.add_container("web",
    image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample"),
    memory_reservation_mi_b=256
)

ecs.FargateService(self, "FargateService",

    cluster=cluster,
    task_definition=task_definition,
    min_healthy_percent=100,
    capacity_provider_strategies=[ecs.CapacityProviderStrategy(
        capacity_provider=mi_capacity_provider_custom.capacity_provider_name,
        weight=1
    )
    ]
)
java
Vpc vpc;


Cluster cluster = Cluster.Builder.create(this, "Cluster").vpc(vpc).build();

// Add your custom policies to the role.
Role customInstanceRole = Role.Builder.create(this, "CustomInstanceRole")
        .assumedBy(new ServicePrincipal("ec2.amazonaws.com"))
        .build();

InstanceProfile customInstanceProfile = InstanceProfile.Builder.create(this, "CustomInstanceProfile")
        .role(customInstanceRole)
        .build();

// Add your custom policies to the role.
Role customInfrastructureRole = Role.Builder.create(this, "CustomInfrastructureRole")
        .assumedBy(new ServicePrincipal("ecs.amazonaws.com"))
        .build();

// Add PassRole permission to allow ECS to pass the instance role to EC2.
customInfrastructureRole.addToPolicy(PolicyStatement.Builder.create()
        .effect(Effect.ALLOW)
        .actions(List.of("iam:PassRole"))
        .resources(List.of(customInstanceRole.getRoleArn()))
        .conditions(Map.of(
                "StringEquals", Map.of(
                        "iam:PassedToService", "ec2.amazonaws.com")))
        .build());

SecurityGroup securityGroup = SecurityGroup.Builder.create(this, "SecurityGroup")
        .vpc(vpc)
        .description("Security group for managed instances")
        .build();

ManagedInstancesCapacityProvider miCapacityProviderCustom = ManagedInstancesCapacityProvider.Builder.create(this, "MICapacityProviderCustomRoles")
        .infrastructureRole(customInfrastructureRole)
        .ec2InstanceProfile(customInstanceProfile)
        .subnets(vpc.getPrivateSubnets())
        .securityGroups(List.of(securityGroup))
        .build();

// Add the capacity provider to the cluster
cluster.addManagedInstancesCapacityProvider(miCapacityProviderCustom);

TaskDefinition taskDefinition = TaskDefinition.Builder.create(this, "TaskDef")
        .memoryMiB("512")
        .cpu("256")
        .networkMode(NetworkMode.AWS_VPC)
        .compatibility(Compatibility.MANAGED_INSTANCES)
        .build();

taskDefinition.addContainer("web", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
        .memoryReservationMiB(256)
        .build());

FargateService.Builder.create(this, "FargateService")

        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .minHealthyPercent(100)
        .capacityProviderStrategies(List.of(CapacityProviderStrategy.builder()
                .capacityProvider(miCapacityProviderCustom.getCapacityProviderName())
                .weight(1)
                .build()))
        .build();
csharp
Vpc vpc;


var cluster = new Cluster(this, "Cluster", new ClusterProps { Vpc = vpc });

// Add your custom policies to the role.
var customInstanceRole = new Role(this, "CustomInstanceRole", new RoleProps {
    AssumedBy = new ServicePrincipal("ec2.amazonaws.com")
});

var customInstanceProfile = new InstanceProfile(this, "CustomInstanceProfile", new InstanceProfileProps {
    Role = customInstanceRole
});

// Add your custom policies to the role.
var customInfrastructureRole = new Role(this, "CustomInfrastructureRole", new RoleProps {
    AssumedBy = new ServicePrincipal("ecs.amazonaws.com")
});

// Add PassRole permission to allow ECS to pass the instance role to EC2.
customInfrastructureRole.AddToPolicy(new PolicyStatement(new PolicyStatementProps {
    Effect = Effect.ALLOW,
    Actions = new [] { "iam:PassRole" },
    Resources = new [] { customInstanceRole.RoleArn },
    Conditions = new Dictionary<string, object> {
        { "StringEquals", new Dictionary<string, string> {
            { "iam:PassedToService", "ec2.amazonaws.com" }
        } }
    }
}));

var securityGroup = new SecurityGroup(this, "SecurityGroup", new SecurityGroupProps {
    Vpc = vpc,
    Description = "Security group for managed instances"
});

var miCapacityProviderCustom = new ManagedInstancesCapacityProvider(this, "MICapacityProviderCustomRoles", new ManagedInstancesCapacityProviderProps {
    InfrastructureRole = customInfrastructureRole,
    Ec2InstanceProfile = customInstanceProfile,
    Subnets = vpc.PrivateSubnets,
    SecurityGroups = new [] { securityGroup }
});

// Add the capacity provider to the cluster
cluster.AddManagedInstancesCapacityProvider(miCapacityProviderCustom);

var taskDefinition = new TaskDefinition(this, "TaskDef", new TaskDefinitionProps {
    MemoryMiB = "512",
    Cpu = "256",
    NetworkMode = NetworkMode.AWS_VPC,
    Compatibility = Compatibility.MANAGED_INSTANCES
});

taskDefinition.AddContainer("web", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
    MemoryReservationMiB = 256
});

new FargateService(this, "FargateService", new FargateServiceProps {

    Cluster = cluster,
    TaskDefinition = taskDefinition,
    MinHealthyPercent = 100,
    CapacityProviderStrategies = new [] { new CapacityProviderStrategy {
        CapacityProvider = miCapacityProviderCustom.CapacityProviderName,
        Weight = 1
    } }
});
go
var vpc Vpc


cluster := ecs.NewCluster(this, jsii.String("Cluster"), &ClusterProps{
	Vpc: Vpc,
})

// Add your custom policies to the role.
customInstanceRole := iam.NewRole(this, jsii.String("CustomInstanceRole"), &RoleProps{
	AssumedBy: iam.NewServicePrincipal(jsii.String("ec2.amazonaws.com")),
})

customInstanceProfile := iam.NewInstanceProfile(this, jsii.String("CustomInstanceProfile"), &InstanceProfileProps{
	Role: customInstanceRole,
})

// Add your custom policies to the role.
customInfrastructureRole := iam.NewRole(this, jsii.String("CustomInfrastructureRole"), &RoleProps{
	AssumedBy: iam.NewServicePrincipal(jsii.String("ecs.amazonaws.com")),
})

// Add PassRole permission to allow ECS to pass the instance role to EC2.
customInfrastructureRole.AddToPolicy(iam.NewPolicyStatement(&PolicyStatementProps{
	Effect: iam.Effect_ALLOW,
	Actions: []*string{
		jsii.String("iam:PassRole"),
	},
	Resources: []*string{
		customInstanceRole.roleArn,
	},
	Conditions: map[string]interface{}{
		"StringEquals": map[string]*string{
			"iam:PassedToService": jsii.String("ec2.amazonaws.com"),
		},
	},
}))

securityGroup := ec2.NewSecurityGroup(this, jsii.String("SecurityGroup"), &SecurityGroupProps{
	Vpc: Vpc,
	Description: jsii.String("Security group for managed instances"),
})

miCapacityProviderCustom := ecs.NewManagedInstancesCapacityProvider(this, jsii.String("MICapacityProviderCustomRoles"), &ManagedInstancesCapacityProviderProps{
	InfrastructureRole: customInfrastructureRole,
	Ec2InstanceProfile: customInstanceProfile,
	Subnets: vpc.PrivateSubnets,
	SecurityGroups: []ISecurityGroup{
		securityGroup,
	},
})

// Add the capacity provider to the cluster
cluster.AddManagedInstancesCapacityProvider(miCapacityProviderCustom)

taskDefinition := ecs.NewTaskDefinition(this, jsii.String("TaskDef"), &TaskDefinitionProps{
	MemoryMiB: jsii.String("512"),
	Cpu: jsii.String("256"),
	NetworkMode: ecs.NetworkMode_AWS_VPC,
	Compatibility: ecs.Compatibility_MANAGED_INSTANCES,
})

taskDefinition.AddContainer(jsii.String("web"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	MemoryReservationMiB: jsii.Number(256),
})

ecs.NewFargateService(this, jsii.String("FargateService"), &FargateServiceProps{

	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	MinHealthyPercent: jsii.Number(100),
	CapacityProviderStrategies: []CapacityProviderStrategy{
		&CapacityProviderStrategy{
			CapacityProvider: miCapacityProviderCustom.CapacityProviderName,
			Weight: jsii.Number(1),
		},
	},
})

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

ts
declare const vpc: ec2.Vpc;

const securityGroup = new ec2.SecurityGroup(this, 'SecurityGroup', {
  vpc,
  description: 'Security group for managed instances',
});

const miCapacityProvider = new ecs.ManagedInstancesCapacityProvider(this, 'MICapacityProvider', {
  subnets: vpc.privateSubnets,
  securityGroups: [securityGroup],
  instanceRequirements: {
    // Required: CPU and memory constraints
    vCpuCountMin: 2,
    vCpuCountMax: 8,
    memoryMin: Size.gibibytes(4),
    memoryMax: Size.gibibytes(32),

    // CPU preferences
    cpuManufacturers: [ec2.CpuManufacturer.INTEL, ec2.CpuManufacturer.AMD],
    instanceGenerations: [ec2.InstanceGeneration.CURRENT],

    // Instance type filtering
    allowedInstanceTypes: ['m5.*', 'c5.*'],

    // Performance characteristics
    burstablePerformance: ec2.BurstablePerformance.EXCLUDED,
    bareMetal: ec2.BareMetal.EXCLUDED,

    // Accelerator requirements (for ML/AI workloads)
    acceleratorTypes: [ec2.AcceleratorType.GPU],
    acceleratorManufacturers: [ec2.AcceleratorManufacturer.NVIDIA],
    acceleratorNames: [ec2.AcceleratorName.T4, ec2.AcceleratorName.V100],
    acceleratorCountMin: 1,

    // Storage requirements
    localStorage: ec2.LocalStorage.REQUIRED,
    localStorageTypes: [ec2.LocalStorageType.SSD],
    totalLocalStorageGBMin: 100,

    // Network requirements
    networkInterfaceCountMin: 2,
    networkBandwidthGbpsMin: 10,

    // Cost optimization
    onDemandMaxPricePercentageOverLowestPrice: 10,
  },
});
python
# vpc: ec2.Vpc


security_group = ec2.SecurityGroup(self, "SecurityGroup",
    vpc=vpc,
    description="Security group for managed instances"
)

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

        # CPU preferences
        cpu_manufacturers=[ec2.CpuManufacturer.INTEL, ec2.CpuManufacturer.AMD],
        instance_generations=[ec2.InstanceGeneration.CURRENT],

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

        # Performance characteristics
        burstable_performance=ec2.BurstablePerformance.EXCLUDED,
        bare_metal=ec2.BareMetal.EXCLUDED,

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

        # Storage requirements
        local_storage=ec2.LocalStorage.REQUIRED,
        local_storage_types=[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
    )
)
java
Vpc vpc;


SecurityGroup securityGroup = SecurityGroup.Builder.create(this, "SecurityGroup")
        .vpc(vpc)
        .description("Security group for managed instances")
        .build();

ManagedInstancesCapacityProvider miCapacityProvider = ManagedInstancesCapacityProvider.Builder.create(this, "MICapacityProvider")
        .subnets(vpc.getPrivateSubnets())
        .securityGroups(List.of(securityGroup))
        .instanceRequirements(InstanceRequirementsConfig.builder()
                // Required: CPU and memory constraints
                .vCpuCountMin(2)
                .vCpuCountMax(8)
                .memoryMin(Size.gibibytes(4))
                .memoryMax(Size.gibibytes(32))

                // CPU preferences
                .cpuManufacturers(List.of(CpuManufacturer.INTEL, CpuManufacturer.AMD))
                .instanceGenerations(List.of(InstanceGeneration.CURRENT))

                // Instance type filtering
                .allowedInstanceTypes(List.of("m5.*", "c5.*"))

                // Performance characteristics
                .burstablePerformance(BurstablePerformance.EXCLUDED)
                .bareMetal(BareMetal.EXCLUDED)

                // Accelerator requirements (for ML/AI workloads)
                .acceleratorTypes(List.of(AcceleratorType.GPU))
                .acceleratorManufacturers(List.of(AcceleratorManufacturer.NVIDIA))
                .acceleratorNames(List.of(AcceleratorName.T4, AcceleratorName.V100))
                .acceleratorCountMin(1)

                // Storage requirements
                .localStorage(LocalStorage.REQUIRED)
                .localStorageTypes(List.of(LocalStorageType.SSD))
                .totalLocalStorageGBMin(100)

                // Network requirements
                .networkInterfaceCountMin(2)
                .networkBandwidthGbpsMin(10)

                // Cost optimization
                .onDemandMaxPricePercentageOverLowestPrice(10)
                .build())
        .build();
csharp
Vpc vpc;


var securityGroup = new SecurityGroup(this, "SecurityGroup", new SecurityGroupProps {
    Vpc = vpc,
    Description = "Security group for managed instances"
});

var miCapacityProvider = new ManagedInstancesCapacityProvider(this, "MICapacityProvider", new ManagedInstancesCapacityProviderProps {
    Subnets = vpc.PrivateSubnets,
    SecurityGroups = new [] { securityGroup },
    InstanceRequirements = new InstanceRequirementsConfig {
        // Required: CPU and memory constraints
        VCpuCountMin = 2,
        VCpuCountMax = 8,
        MemoryMin = Size.Gibibytes(4),
        MemoryMax = Size.Gibibytes(32),

        // CPU preferences
        CpuManufacturers = new [] { CpuManufacturer.INTEL, CpuManufacturer.AMD },
        InstanceGenerations = new [] { InstanceGeneration.CURRENT },

        // Instance type filtering
        AllowedInstanceTypes = new [] { "m5.*", "c5.*" },

        // Performance characteristics
        BurstablePerformance = BurstablePerformance.EXCLUDED,
        BareMetal = BareMetal.EXCLUDED,

        // Accelerator requirements (for ML/AI workloads)
        AcceleratorTypes = new [] { AcceleratorType.GPU },
        AcceleratorManufacturers = new [] { AcceleratorManufacturer.NVIDIA },
        AcceleratorNames = new [] { AcceleratorName.T4, AcceleratorName.V100 },
        AcceleratorCountMin = 1,

        // Storage requirements
        LocalStorage = LocalStorage.REQUIRED,
        LocalStorageTypes = new [] { LocalStorageType.SSD },
        TotalLocalStorageGBMin = 100,

        // Network requirements
        NetworkInterfaceCountMin = 2,
        NetworkBandwidthGbpsMin = 10,

        // Cost optimization
        OnDemandMaxPricePercentageOverLowestPrice = 10
    }
});
go
var vpc Vpc


securityGroup := ec2.NewSecurityGroup(this, jsii.String("SecurityGroup"), &SecurityGroupProps{
	Vpc: Vpc,
	Description: jsii.String("Security group for managed instances"),
})

miCapacityProvider := ecs.NewManagedInstancesCapacityProvider(this, jsii.String("MICapacityProvider"), &ManagedInstancesCapacityProviderProps{
	Subnets: vpc.PrivateSubnets,
	SecurityGroups: []ISecurityGroup{
		securityGroup,
	},
	InstanceRequirements: &InstanceRequirementsConfig{
		// Required: CPU and memory constraints
		VCpuCountMin: jsii.Number(2),
		VCpuCountMax: jsii.Number(8),
		MemoryMin: awscdk.Size_Gibibytes(jsii.Number(4)),
		MemoryMax: awscdk.Size_*Gibibytes(jsii.Number(32)),

		// CPU preferences
		CpuManufacturers: []CpuManufacturer{
			ec2.CpuManufacturer_INTEL,
			ec2.CpuManufacturer_AMD,
		},
		InstanceGenerations: []InstanceGeneration{
			ec2.InstanceGeneration_CURRENT,
		},

		// Instance type filtering
		AllowedInstanceTypes: []*string{
			jsii.String("m5.*"),
			jsii.String("c5.*"),
		},

		// Performance characteristics
		BurstablePerformance: ec2.BurstablePerformance_EXCLUDED,
		BareMetal: ec2.BareMetal_EXCLUDED,

		// Accelerator requirements (for ML/AI workloads)
		AcceleratorTypes: []AcceleratorType{
			ec2.AcceleratorType_GPU,
		},
		AcceleratorManufacturers: []AcceleratorManufacturer{
			ec2.AcceleratorManufacturer_NVIDIA,
		},
		AcceleratorNames: []AcceleratorName{
			ec2.AcceleratorName_T4,
			ec2.AcceleratorName_V100,
		},
		AcceleratorCountMin: jsii.Number(1),

		// Storage requirements
		LocalStorage: ec2.LocalStorage_REQUIRED,
		LocalStorageTypes: []LocalStorageType{
			ec2.LocalStorageType_SSD,
		},
		TotalLocalStorageGBMin: jsii.Number(100),

		// Network requirements
		NetworkInterfaceCountMin: jsii.Number(2),
		NetworkBandwidthGbpsMin: jsii.Number(10),

		// Cost optimization
		OnDemandMaxPricePercentageOverLowestPrice: jsii.Number(10),
	},
})

Note: Service Replacement When Migrating from LaunchType to CapacityProviderStrategy ​

Understanding the Limitation

The ECS CreateService API does not allow specifying both launchType and capacityProviderStrategies simultaneously. When you specify capacityProviderStrategies, the CDK uses those capacity providers instead of a launch type. This is a limitation of the ECS API and CloudFormation, not a CDK bug.

Impact on Updates

Because launchType is immutable during updates, switching from launchType to capacityProviderStrategies requires CloudFormation to replace the service. This means your existing service will be deleted and recreated with the new configuration. This behavior is expected and reflects the underlying API constraints.

Workaround

While we work on a long-term solution, you can use the following escape hatch to preserve your service during the migration:

ts
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;
declare const miCapacityProvider: ecs.ManagedInstancesCapacityProvider;

const service = new ecs.FargateService(this, 'Service', {
  cluster,
  taskDefinition,
  capacityProviderStrategies: [
    {
      capacityProvider: miCapacityProvider.capacityProviderName,
      weight: 1,
    },
  ],
});

// Escape hatch: Force launchType at the CloudFormation level to prevent service replacement
const cfnService = service.node.defaultChild as ecs.CfnService;
cfnService.launchType = 'FARGATE'; // or 'FARGATE_SPOT' depending on your capacity provider
python
# cluster: ecs.Cluster
# task_definition: ecs.TaskDefinition
# mi_capacity_provider: ecs.ManagedInstancesCapacityProvider


service = ecs.FargateService(self, "Service",
    cluster=cluster,
    task_definition=task_definition,
    capacity_provider_strategies=[ecs.CapacityProviderStrategy(
        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"
java
Cluster cluster;
TaskDefinition taskDefinition;
ManagedInstancesCapacityProvider miCapacityProvider;


FargateService service = FargateService.Builder.create(this, "Service")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .capacityProviderStrategies(List.of(CapacityProviderStrategy.builder()
                .capacityProvider(miCapacityProvider.getCapacityProviderName())
                .weight(1)
                .build()))
        .build();

// Escape hatch: Force launchType at the CloudFormation level to prevent service replacement
CfnService cfnService = (CfnService)service.getNode().getDefaultChild();
cfnService.getLaunchType() = "FARGATE";
csharp
Cluster cluster;
TaskDefinition taskDefinition;
ManagedInstancesCapacityProvider miCapacityProvider;


var service = new FargateService(this, "Service", new FargateServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    CapacityProviderStrategies = new [] { new CapacityProviderStrategy {
        CapacityProvider = miCapacityProvider.CapacityProviderName,
        Weight = 1
    } }
});

// Escape hatch: Force launchType at the CloudFormation level to prevent service replacement
var cfnService = (CfnService)service.Node.DefaultChild;
cfnService.LaunchType = "FARGATE";
go
var cluster Cluster
var taskDefinition TaskDefinition
var miCapacityProvider ManagedInstancesCapacityProvider


service := ecs.NewFargateService(this, jsii.String("Service"), &FargateServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	CapacityProviderStrategies: []CapacityProviderStrategy{
		&CapacityProviderStrategy{
			CapacityProvider: miCapacityProvider.CapacityProviderName,
			Weight: jsii.Number(1),
		},
	},
})

// Escape hatch: Force launchType at the CloudFormation level to prevent service replacement
cfnService := service.Node.defaultChild.(CfnService)
cfnService.launchType = "FARGATE"

Cluster Default Provider Strategy ​

A capacity provider strategy determines whether ECS tasks are launched on EC2 instances or Fargate/Fargate Spot. It can be specified at the cluster, service, or task level, and consists of one or more capacity providers. You can specify an optional base and weight value for finer control of how tasks are launched. The base specifies a minimum number of tasks on one capacity provider, and the weights of each capacity provider determine how tasks are distributed after base is satisfied.

You can associate a default capacity provider strategy with an Amazon ECS cluster. After you do this, a default capacity provider strategy is used when creating a service or running a standalone task in the cluster and whenever a custom capacity provider strategy or a launch type isn't specified. We recommend that you define a default capacity provider strategy for each cluster.

For more information visit https://docs.aws.amazon.com/AmazonECS/latest/developerguide/cluster-capacity-providers.html

When the service does not have a capacity provider strategy, the cluster's default capacity provider strategy will be used. Default Capacity Provider Strategy can be added by using the method addDefaultCapacityProviderStrategy. A capacity provider strategy cannot contain a mix of EC2 Autoscaling Group capacity providers and Fargate providers.

ts
declare const capacityProvider: ecs.AsgCapacityProvider;

const cluster = new ecs.Cluster(this, 'EcsCluster', {
  enableFargateCapacityProviders: true,
});
cluster.addAsgCapacityProvider(capacityProvider);

cluster.addDefaultCapacityProviderStrategy([
  { capacityProvider: 'FARGATE', base: 10, weight: 50 },
  { capacityProvider: 'FARGATE_SPOT', weight: 50 },
]);
python
# capacity_provider: ecs.AsgCapacityProvider


cluster = ecs.Cluster(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
])
java
AsgCapacityProvider capacityProvider;


Cluster cluster = Cluster.Builder.create(this, "EcsCluster")
        .enableFargateCapacityProviders(true)
        .build();
cluster.addAsgCapacityProvider(capacityProvider);

cluster.addDefaultCapacityProviderStrategy(List.of(CapacityProviderStrategy.builder().capacityProvider("FARGATE").base(10).weight(50).build(), CapacityProviderStrategy.builder().capacityProvider("FARGATE_SPOT").weight(50).build()));
csharp
AsgCapacityProvider capacityProvider;


var cluster = new Cluster(this, "EcsCluster", new ClusterProps {
    EnableFargateCapacityProviders = true
});
cluster.AddAsgCapacityProvider(capacityProvider);

cluster.AddDefaultCapacityProviderStrategy(new [] { new CapacityProviderStrategy { CapacityProvider = "FARGATE", Base = 10, Weight = 50 }, new CapacityProviderStrategy { CapacityProvider = "FARGATE_SPOT", Weight = 50 } });
go
var capacityProvider AsgCapacityProvider


cluster := ecs.NewCluster(this, jsii.String("EcsCluster"), &ClusterProps{
	EnableFargateCapacityProviders: jsii.Boolean(true),
})
cluster.AddAsgCapacityProvider(capacityProvider)

cluster.AddDefaultCapacityProviderStrategy([]CapacityProviderStrategy{
	&CapacityProviderStrategy{
		CapacityProvider: jsii.String("FARGATE"),
		Base: jsii.Number(10),
		Weight: jsii.Number(50),
	},
	&CapacityProviderStrategy{
		CapacityProvider: jsii.String("FARGATE_SPOT"),
		Weight: jsii.Number(50),
	},
})
ts
declare const capacityProvider: ecs.AsgCapacityProvider;

const cluster = new ecs.Cluster(this, 'EcsCluster', {
  enableFargateCapacityProviders: true,
});
cluster.addAsgCapacityProvider(capacityProvider);

cluster.addDefaultCapacityProviderStrategy([
  { capacityProvider: capacityProvider.capacityProviderName },
]);
python
# capacity_provider: ecs.AsgCapacityProvider


cluster = ecs.Cluster(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
])
java
AsgCapacityProvider capacityProvider;


Cluster cluster = Cluster.Builder.create(this, "EcsCluster")
        .enableFargateCapacityProviders(true)
        .build();
cluster.addAsgCapacityProvider(capacityProvider);

cluster.addDefaultCapacityProviderStrategy(List.of(CapacityProviderStrategy.builder().capacityProvider(capacityProvider.getCapacityProviderName()).build()));
csharp
AsgCapacityProvider capacityProvider;


var cluster = new Cluster(this, "EcsCluster", new ClusterProps {
    EnableFargateCapacityProviders = true
});
cluster.AddAsgCapacityProvider(capacityProvider);

cluster.AddDefaultCapacityProviderStrategy(new [] { new CapacityProviderStrategy { CapacityProvider = capacityProvider.CapacityProviderName } });
go
var capacityProvider AsgCapacityProvider


cluster := ecs.NewCluster(this, jsii.String("EcsCluster"), &ClusterProps{
	EnableFargateCapacityProviders: jsii.Boolean(true),
})
cluster.AddAsgCapacityProvider(capacityProvider)

cluster.AddDefaultCapacityProviderStrategy([]CapacityProviderStrategy{
	&CapacityProviderStrategy{
		CapacityProvider: capacityProvider.CapacityProviderName,
	},
})

Elastic Inference Accelerators ​

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

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

ts
const inferenceAccelerators = [{
  deviceName: 'device1',
  deviceType: 'eia2.medium',
}];

const taskDefinition = new ecs.Ec2TaskDefinition(this, 'Ec2TaskDef', {
  inferenceAccelerators,
});
python
inference_accelerators = [{
    "device_name": "device1",
    "device_type": "eia2.medium"
}]

task_definition = ecs.Ec2TaskDefinition(self, "Ec2TaskDef",
    inference_accelerators=inference_accelerators
)
java
Map<String, String>[] inferenceAccelerators = List.of(Map.of(
        "deviceName", "device1",
        "deviceType", "eia2.medium"));

Ec2TaskDefinition taskDefinition = Ec2TaskDefinition.Builder.create(this, "Ec2TaskDef")
        .inferenceAccelerators(inferenceAccelerators)
        .build();
csharp
IDictionary<string, string>[] inferenceAccelerators = new [] { new Dictionary<string, string> {
    { "deviceName", "device1" },
    { "deviceType", "eia2.medium" }
} };

var taskDefinition = new Ec2TaskDefinition(this, "Ec2TaskDef", new Ec2TaskDefinitionProps {
    InferenceAccelerators = inferenceAccelerators
});
go
inferenceAccelerators := []map[string]*string{
	map[string]*string{
		"deviceName": jsii.String("device1"),
		"deviceType": jsii.String("eia2.medium"),
	},
}

taskDefinition := ecs.NewEc2TaskDefinition(this, jsii.String("Ec2TaskDef"), &Ec2TaskDefinitionProps{
	InferenceAccelerators: InferenceAccelerators,
})

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

ts
declare const taskDefinition: ecs.TaskDefinition;
const inferenceAcceleratorResources = ['device1'];

taskDefinition.addContainer('cont', {
  image: ecs.ContainerImage.fromRegistry('test'),
  memoryLimitMiB: 1024,
  inferenceAcceleratorResources,
});
python
# task_definition: ecs.TaskDefinition

inference_accelerator_resources = ["device1"]

task_definition.add_container("cont",
    image=ecs.ContainerImage.from_registry("test"),
    memory_limit_mi_b=1024,
    inference_accelerator_resources=inference_accelerator_resources
)
java
TaskDefinition taskDefinition;

String[] inferenceAcceleratorResources = List.of("device1");

taskDefinition.addContainer("cont", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("test"))
        .memoryLimitMiB(1024)
        .inferenceAcceleratorResources(inferenceAcceleratorResources)
        .build());
csharp
TaskDefinition taskDefinition;

var inferenceAcceleratorResources = new [] { "device1" };

taskDefinition.AddContainer("cont", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("test"),
    MemoryLimitMiB = 1024,
    InferenceAcceleratorResources = inferenceAcceleratorResources
});
go
var taskDefinition TaskDefinition

inferenceAcceleratorResources := []*string{
	"device1",
}

taskDefinition.AddContainer(jsii.String("cont"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("test")),
	MemoryLimitMiB: jsii.Number(1024),
	InferenceAcceleratorResources: InferenceAcceleratorResources,
})

ECS Exec command ​

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

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

ts
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;

const service = new ecs.Ec2Service(this, 'Service', {
  cluster,
  taskDefinition,
  minHealthyPercent: 100,
  enableExecuteCommand: true,
});
python
# cluster: ecs.Cluster
# task_definition: ecs.TaskDefinition


service = ecs.Ec2Service(self, "Service",
    cluster=cluster,
    task_definition=task_definition,
    min_healthy_percent=100,
    enable_execute_command=True
)
java
Cluster cluster;
TaskDefinition taskDefinition;


Ec2Service service = Ec2Service.Builder.create(this, "Service")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .minHealthyPercent(100)
        .enableExecuteCommand(true)
        .build();
csharp
Cluster cluster;
TaskDefinition taskDefinition;


var service = new Ec2Service(this, "Service", new Ec2ServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    MinHealthyPercent = 100,
    EnableExecuteCommand = true
});
go
var cluster Cluster
var taskDefinition TaskDefinition


service := ecs.NewEc2Service(this, jsii.String("Service"), &Ec2ServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	MinHealthyPercent: jsii.Number(100),
	EnableExecuteCommand: jsii.Boolean(true),
})

Enabling logging ​

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

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

ts
declare const vpc: ec2.Vpc;
const kmsKey = new kms.Key(this, 'KmsKey');

// Pass the KMS key in the `encryptionKey` field to associate the key to the log group
const logGroup = new logs.LogGroup(this, 'LogGroup', {
  encryptionKey: kmsKey,
});

// Pass the KMS key in the `encryptionKey` field to associate the key to the S3 bucket
const execBucket = new s3.Bucket(this, 'EcsExecBucket', {
  encryptionKey: kmsKey,
});

const cluster = new ecs.Cluster(this, 'Cluster', {
  vpc,
  executeCommandConfiguration: {
    kmsKey,
    logConfiguration: {
      cloudWatchLogGroup: logGroup,
      cloudWatchEncryptionEnabled: true,
      s3Bucket: execBucket,
      s3EncryptionEnabled: true,
      s3KeyPrefix: 'exec-command-output',
    },
    logging: ecs.ExecuteCommandLogging.OVERRIDE,
  },
});
python
# vpc: ec2.Vpc

kms_key = kms.Key(self, "KmsKey")

# Pass the KMS key in the `encryptionKey` field to associate the key to the log group
log_group = logs.LogGroup(self, "LogGroup",
    encryption_key=kms_key
)

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

cluster = ecs.Cluster(self, "Cluster",
    vpc=vpc,
    execute_command_configuration=ecs.ExecuteCommandConfiguration(
        kms_key=kms_key,
        log_configuration=ecs.ExecuteCommandLogConfiguration(
            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=ecs.ExecuteCommandLogging.OVERRIDE
    )
)
java
Vpc vpc;

Key kmsKey = new Key(this, "KmsKey");

// Pass the KMS key in the `encryptionKey` field to associate the key to the log group
LogGroup logGroup = LogGroup.Builder.create(this, "LogGroup")
        .encryptionKey(kmsKey)
        .build();

// Pass the KMS key in the `encryptionKey` field to associate the key to the S3 bucket
Bucket execBucket = Bucket.Builder.create(this, "EcsExecBucket")
        .encryptionKey(kmsKey)
        .build();

Cluster cluster = Cluster.Builder.create(this, "Cluster")
        .vpc(vpc)
        .executeCommandConfiguration(ExecuteCommandConfiguration.builder()
                .kmsKey(kmsKey)
                .logConfiguration(ExecuteCommandLogConfiguration.builder()
                        .cloudWatchLogGroup(logGroup)
                        .cloudWatchEncryptionEnabled(true)
                        .s3Bucket(execBucket)
                        .s3EncryptionEnabled(true)
                        .s3KeyPrefix("exec-command-output")
                        .build())
                .logging(ExecuteCommandLogging.OVERRIDE)
                .build())
        .build();
csharp
Vpc vpc;

var kmsKey = new Key(this, "KmsKey");

// Pass the KMS key in the `encryptionKey` field to associate the key to the log group
var logGroup = new LogGroup(this, "LogGroup", new LogGroupProps {
    EncryptionKey = kmsKey
});

// Pass the KMS key in the `encryptionKey` field to associate the key to the S3 bucket
var execBucket = new Bucket(this, "EcsExecBucket", new BucketProps {
    EncryptionKey = kmsKey
});

var cluster = new Cluster(this, "Cluster", new ClusterProps {
    Vpc = vpc,
    ExecuteCommandConfiguration = new ExecuteCommandConfiguration {
        KmsKey = kmsKey,
        LogConfiguration = new ExecuteCommandLogConfiguration {
            CloudWatchLogGroup = logGroup,
            CloudWatchEncryptionEnabled = true,
            S3Bucket = execBucket,
            S3EncryptionEnabled = true,
            S3KeyPrefix = "exec-command-output"
        },
        Logging = ExecuteCommandLogging.OVERRIDE
    }
});
go
var vpc Vpc

kmsKey := kms.NewKey(this, jsii.String("KmsKey"))

// Pass the KMS key in the `encryptionKey` field to associate the key to the log group
logGroup := logs.NewLogGroup(this, jsii.String("LogGroup"), &LogGroupProps{
	EncryptionKey: kmsKey,
})

// Pass the KMS key in the `encryptionKey` field to associate the key to the S3 bucket
execBucket := s3.NewBucket(this, jsii.String("EcsExecBucket"), &BucketProps{
	EncryptionKey: kmsKey,
})

cluster := ecs.NewCluster(this, jsii.String("Cluster"), &ClusterProps{
	Vpc: Vpc,
	ExecuteCommandConfiguration: &ExecuteCommandConfiguration{
		KmsKey: *KmsKey,
		LogConfiguration: &ExecuteCommandLogConfiguration{
			CloudWatchLogGroup: logGroup,
			CloudWatchEncryptionEnabled: jsii.Boolean(true),
			S3Bucket: execBucket,
			S3EncryptionEnabled: jsii.Boolean(true),
			S3KeyPrefix: jsii.String("exec-command-output"),
		},
		Logging: 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.

ts
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;
declare const containerOptions: ecs.ContainerDefinitionOptions;

const container = taskDefinition.addContainer('MyContainer', containerOptions);

container.addPortMappings({
  name: 'api',
  containerPort: 8080,
});

cluster.addDefaultCloudMapNamespace({
  name: 'local',
});

const service = new ecs.FargateService(this, 'Service', {
  cluster,
  taskDefinition,
  minHealthyPercent: 100,
  serviceConnectConfiguration: {
    services: [
      {
        portMappingName: 'api',
        dnsName: 'http-api',
        port: 80,
      },
    ],
  },
});
python
# cluster: ecs.Cluster
# task_definition: ecs.TaskDefinition
# container_options: 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 = ecs.FargateService(self, "Service",
    cluster=cluster,
    task_definition=task_definition,
    min_healthy_percent=100,
    service_connect_configuration=ecs.ServiceConnectProps(
        services=[ecs.ServiceConnectService(
            port_mapping_name="api",
            dns_name="http-api",
            port=80
        )
        ]
    )
)
java
Cluster cluster;
TaskDefinition taskDefinition;
ContainerDefinitionOptions containerOptions;


ContainerDefinition container = taskDefinition.addContainer("MyContainer", containerOptions);

container.addPortMappings(PortMapping.builder()
        .name("api")
        .containerPort(8080)
        .build());

cluster.addDefaultCloudMapNamespace(CloudMapNamespaceOptions.builder()
        .name("local")
        .build());

FargateService service = FargateService.Builder.create(this, "Service")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .minHealthyPercent(100)
        .serviceConnectConfiguration(ServiceConnectProps.builder()
                .services(List.of(ServiceConnectService.builder()
                        .portMappingName("api")
                        .dnsName("http-api")
                        .port(80)
                        .build()))
                .build())
        .build();
csharp
Cluster cluster;
TaskDefinition taskDefinition;
ContainerDefinitionOptions containerOptions;


var container = taskDefinition.AddContainer("MyContainer", containerOptions);

container.AddPortMappings(new PortMapping {
    Name = "api",
    ContainerPort = 8080
});

cluster.AddDefaultCloudMapNamespace(new CloudMapNamespaceOptions {
    Name = "local"
});

var service = new FargateService(this, "Service", new FargateServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    MinHealthyPercent = 100,
    ServiceConnectConfiguration = new ServiceConnectProps {
        Services = new [] { new ServiceConnectService {
            PortMappingName = "api",
            DnsName = "http-api",
            Port = 80
        } }
    }
});
go
var cluster Cluster
var taskDefinition TaskDefinition
var containerOptions ContainerDefinitionOptions


container := taskDefinition.AddContainer(jsii.String("MyContainer"), containerOptions)

container.AddPortMappings(&PortMapping{
	Name: jsii.String("api"),
	ContainerPort: jsii.Number(8080),
})

cluster.AddDefaultCloudMapNamespace(&CloudMapNamespaceOptions{
	Name: jsii.String("local"),
})

service := ecs.NewFargateService(this, jsii.String("Service"), &FargateServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	MinHealthyPercent: jsii.Number(100),
	ServiceConnectConfiguration: &ServiceConnectProps{
		Services: []ServiceConnectService{
			&ServiceConnectService{
				PortMappingName: jsii.String("api"),
				DnsName: jsii.String("http-api"),
				Port: jsii.Number(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.

ts
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;

const service = new ecs.FargateService(this, 'Service', {
  cluster,
  taskDefinition,
  minHealthyPercent: 100,
});
service.enableServiceConnect();
python
# cluster: ecs.Cluster
# task_definition: ecs.TaskDefinition


service = ecs.FargateService(self, "Service",
    cluster=cluster,
    task_definition=task_definition,
    min_healthy_percent=100
)
service.enable_service_connect()
java
Cluster cluster;
TaskDefinition taskDefinition;


FargateService service = FargateService.Builder.create(this, "Service")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .minHealthyPercent(100)
        .build();
service.enableServiceConnect();
csharp
Cluster cluster;
TaskDefinition taskDefinition;


var service = new FargateService(this, "Service", new FargateServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    MinHealthyPercent = 100
});
service.EnableServiceConnect();
go
var cluster Cluster
var taskDefinition TaskDefinition


service := ecs.NewFargateService(this, jsii.String("Service"), &FargateServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	MinHealthyPercent: jsii.Number(100),
})
service.EnableServiceConnect()

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

ts
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;

const customService = new ecs.FargateService(this, 'CustomizedService', {
  cluster,
  taskDefinition,
  minHealthyPercent: 100,
  serviceConnectConfiguration: {
    logDriver: ecs.LogDrivers.awsLogs({
      streamPrefix: 'sc-traffic',
    }),
    services: [
      {
        portMappingName: 'api',
        dnsName: 'customized-api',
        port: 80,
        ingressPortOverride: 20040,
        discoveryName: 'custom',
      },
    ],
  },
});
python
# cluster: ecs.Cluster
# task_definition: ecs.TaskDefinition


custom_service = ecs.FargateService(self, "CustomizedService",
    cluster=cluster,
    task_definition=task_definition,
    min_healthy_percent=100,
    service_connect_configuration=ecs.ServiceConnectProps(
        log_driver=ecs.LogDrivers.aws_logs(
            stream_prefix="sc-traffic"
        ),
        services=[ecs.ServiceConnectService(
            port_mapping_name="api",
            dns_name="customized-api",
            port=80,
            ingress_port_override=20040,
            discovery_name="custom"
        )
        ]
    )
)
java
Cluster cluster;
TaskDefinition taskDefinition;


FargateService customService = FargateService.Builder.create(this, "CustomizedService")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .minHealthyPercent(100)
        .serviceConnectConfiguration(ServiceConnectProps.builder()
                .logDriver(LogDrivers.awsLogs(AwsLogDriverProps.builder()
                        .streamPrefix("sc-traffic")
                        .build()))
                .services(List.of(ServiceConnectService.builder()
                        .portMappingName("api")
                        .dnsName("customized-api")
                        .port(80)
                        .ingressPortOverride(20040)
                        .discoveryName("custom")
                        .build()))
                .build())
        .build();
csharp
Cluster cluster;
TaskDefinition taskDefinition;


var customService = new FargateService(this, "CustomizedService", new FargateServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    MinHealthyPercent = 100,
    ServiceConnectConfiguration = new ServiceConnectProps {
        LogDriver = LogDrivers.AwsLogs(new AwsLogDriverProps {
            StreamPrefix = "sc-traffic"
        }),
        Services = new [] { new ServiceConnectService {
            PortMappingName = "api",
            DnsName = "customized-api",
            Port = 80,
            IngressPortOverride = 20040,
            DiscoveryName = "custom"
        } }
    }
});
go
var cluster Cluster
var taskDefinition TaskDefinition


customService := ecs.NewFargateService(this, jsii.String("CustomizedService"), &FargateServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	MinHealthyPercent: jsii.Number(100),
	ServiceConnectConfiguration: &ServiceConnectProps{
		LogDriver: ecs.LogDrivers_AwsLogs(&AwsLogDriverProps{
			StreamPrefix: jsii.String("sc-traffic"),
		}),
		Services: []ServiceConnectService{
			&ServiceConnectService{
				PortMappingName: jsii.String("api"),
				DnsName: jsii.String("customized-api"),
				Port: jsii.Number(80),
				IngressPortOverride: jsii.Number(20040),
				DiscoveryName: jsii.String("custom"),
			},
		},
	},
})

To set a timeout for service connect, use idleTimeout and perRequestTimeout.

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

ts
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;

const service = new ecs.FargateService(this, 'Service', {
  cluster,
  taskDefinition,
  minHealthyPercent: 100,
  serviceConnectConfiguration: {
    services: [
      {
        portMappingName: 'api',
        idleTimeout: Duration.minutes(5),
        perRequestTimeout: Duration.minutes(5),
      },
    ],
  },
});
python
# cluster: ecs.Cluster
# task_definition: ecs.TaskDefinition


service = ecs.FargateService(self, "Service",
    cluster=cluster,
    task_definition=task_definition,
    min_healthy_percent=100,
    service_connect_configuration=ecs.ServiceConnectProps(
        services=[ecs.ServiceConnectService(
            port_mapping_name="api",
            idle_timeout=Duration.minutes(5),
            per_request_timeout=Duration.minutes(5)
        )
        ]
    )
)
java
Cluster cluster;
TaskDefinition taskDefinition;


FargateService service = FargateService.Builder.create(this, "Service")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .minHealthyPercent(100)
        .serviceConnectConfiguration(ServiceConnectProps.builder()
                .services(List.of(ServiceConnectService.builder()
                        .portMappingName("api")
                        .idleTimeout(Duration.minutes(5))
                        .perRequestTimeout(Duration.minutes(5))
                        .build()))
                .build())
        .build();
csharp
Cluster cluster;
TaskDefinition taskDefinition;


var service = new FargateService(this, "Service", new FargateServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    MinHealthyPercent = 100,
    ServiceConnectConfiguration = new ServiceConnectProps {
        Services = new [] { new ServiceConnectService {
            PortMappingName = "api",
            IdleTimeout = Duration.Minutes(5),
            PerRequestTimeout = Duration.Minutes(5)
        } }
    }
});
go
var cluster Cluster
var taskDefinition TaskDefinition


service := ecs.NewFargateService(this, jsii.String("Service"), &FargateServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	MinHealthyPercent: jsii.Number(100),
	ServiceConnectConfiguration: &ServiceConnectProps{
		Services: []ServiceConnectService{
			&ServiceConnectService{
				PortMappingName: jsii.String("api"),
				IdleTimeout: awscdk.Duration_Minutes(jsii.Number(5)),
				PerRequestTimeout: awscdk.Duration_*Minutes(jsii.Number(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.

ts
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;

const service = new ecs.FargateService(this, 'Service', {
  cluster,
  taskDefinition,
  serviceConnectConfiguration: {
    services: [
      {
        portMappingName: 'api',
      },
    ],
    accessLogConfiguration: {
      format: ecs.ServiceConnectAccessLogFormat.JSON,
      includeQueryParameters: true,
    },
    // When configuring access log,
    // you also need to configure the log driver accordingly.
    logDriver: ecs.LogDrivers.awsLogs({
      streamPrefix: 'prefix',
    }),
  },
});
python
# cluster: ecs.Cluster
# task_definition: ecs.TaskDefinition


service = ecs.FargateService(self, "Service",
    cluster=cluster,
    task_definition=task_definition,
    service_connect_configuration=ecs.ServiceConnectProps(
        services=[ecs.ServiceConnectService(
            port_mapping_name="api"
        )
        ],
        access_log_configuration=ecs.ServiceConnectAccessLogConfiguration(
            format=ecs.ServiceConnectAccessLogFormat.JSON,
            include_query_parameters=True
        ),
        # When configuring access log,
        # you also need to configure the log driver accordingly.
        log_driver=ecs.LogDrivers.aws_logs(
            stream_prefix="prefix"
        )
    )
)
java
Cluster cluster;
TaskDefinition taskDefinition;


FargateService service = FargateService.Builder.create(this, "Service")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .serviceConnectConfiguration(ServiceConnectProps.builder()
                .services(List.of(ServiceConnectService.builder()
                        .portMappingName("api")
                        .build()))
                .accessLogConfiguration(ServiceConnectAccessLogConfiguration.builder()
                        .format(ServiceConnectAccessLogFormat.JSON)
                        .includeQueryParameters(true)
                        .build())
                // When configuring access log,
                // you also need to configure the log driver accordingly.
                .logDriver(LogDrivers.awsLogs(AwsLogDriverProps.builder()
                        .streamPrefix("prefix")
                        .build()))
                .build())
        .build();
csharp
Cluster cluster;
TaskDefinition taskDefinition;


var service = new FargateService(this, "Service", new FargateServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    ServiceConnectConfiguration = new ServiceConnectProps {
        Services = new [] { new ServiceConnectService {
            PortMappingName = "api"
        } },
        AccessLogConfiguration = new ServiceConnectAccessLogConfiguration {
            Format = ServiceConnectAccessLogFormat.JSON,
            IncludeQueryParameters = true
        },
        // When configuring access log,
        // you also need to configure the log driver accordingly.
        LogDriver = LogDrivers.AwsLogs(new AwsLogDriverProps {
            StreamPrefix = "prefix"
        })
    }
});
go
var cluster Cluster
var taskDefinition TaskDefinition


service := ecs.NewFargateService(this, jsii.String("Service"), &FargateServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	ServiceConnectConfiguration: &ServiceConnectProps{
		Services: []ServiceConnectService{
			&ServiceConnectService{
				PortMappingName: jsii.String("api"),
			},
		},
		AccessLogConfiguration: &ServiceConnectAccessLogConfiguration{
			Format: ecs.ServiceConnectAccessLogFormat_JSON,
			IncludeQueryParameters: jsii.Boolean(true),
		},
		// When configuring access log,
		// you also need to configure the log driver accordingly.
		LogDriver: ecs.LogDrivers_AwsLogs(&AwsLogDriverProps{
			StreamPrefix: jsii.String("prefix"),
		}),
	},
})

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

  • ServiceConnectAccessLogFormat.TEXT - Human-readable text format
  • ServiceConnectAccessLogFormat.JSON - Structured JSON format for log analysis tools

The includeQueryParameters 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 kmsKeyId.

You can only attach a single volume for each task in the ECS Service.

To add an empty EBS Volume to an ECS Service, call service.addVolume().

ts
declare const cluster: ecs.Cluster;
const taskDefinition = new ecs.FargateTaskDefinition(this, 'TaskDef');

const container = taskDefinition.addContainer('web', {
  image: ecs.ContainerImage.fromRegistry('amazon/amazon-ecs-sample'),
  portMappings: [{
    containerPort: 80,
    protocol: ecs.Protocol.TCP,
  }],
});

const volume = new ecs.ServiceManagedVolume(this, 'EBSVolume', {
  name: 'ebs1',
  managedEBSVolume: {
    size: Size.gibibytes(15),
    volumeType: ec2.EbsDeviceVolumeType.GP3,
    fileSystemType: ecs.FileSystemType.XFS,
    tagSpecifications: [{
      tags: {
        purpose: 'production',
      },
      propagateTags: ecs.EbsPropagatedTagSource.SERVICE,
    }],
  },
});

volume.mountIn(container, {
  containerPath: '/var/lib',
  readOnly: false,
});

taskDefinition.addVolume(volume);

const service = new ecs.FargateService(this, 'FargateService', {
  cluster,
  taskDefinition,
  minHealthyPercent: 100,
});

service.addVolume(volume);
python
# cluster: ecs.Cluster

task_definition = ecs.FargateTaskDefinition(self, "TaskDef")

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

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

volume.mount_in(container,
    container_path="/var/lib",
    read_only=False
)

task_definition.add_volume(volume)

service = ecs.FargateService(self, "FargateService",
    cluster=cluster,
    task_definition=task_definition,
    min_healthy_percent=100
)

service.add_volume(volume)
java
Cluster cluster;

FargateTaskDefinition taskDefinition = new FargateTaskDefinition(this, "TaskDef");

ContainerDefinition container = taskDefinition.addContainer("web", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
        .portMappings(List.of(PortMapping.builder()
                .containerPort(80)
                .protocol(Protocol.TCP)
                .build()))
        .build());

ServiceManagedVolume volume = ServiceManagedVolume.Builder.create(this, "EBSVolume")
        .name("ebs1")
        .managedEBSVolume(ServiceManagedEBSVolumeConfiguration.builder()
                .size(Size.gibibytes(15))
                .volumeType(EbsDeviceVolumeType.GP3)
                .fileSystemType(FileSystemType.XFS)
                .tagSpecifications(List.of(EBSTagSpecification.builder()
                        .tags(Map.of(
                                "purpose", "production"))
                        .propagateTags(EbsPropagatedTagSource.SERVICE)
                        .build()))
                .build())
        .build();

volume.mountIn(container, ContainerMountPoint.builder()
        .containerPath("/var/lib")
        .readOnly(false)
        .build());

taskDefinition.addVolume(volume);

FargateService service = FargateService.Builder.create(this, "FargateService")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .minHealthyPercent(100)
        .build();

service.addVolume(volume);
csharp
Cluster cluster;

var taskDefinition = new FargateTaskDefinition(this, "TaskDef");

var container = taskDefinition.AddContainer("web", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
    PortMappings = new [] { new PortMapping {
        ContainerPort = 80,
        Protocol = Protocol.TCP
    } }
});

var volume = new ServiceManagedVolume(this, "EBSVolume", new ServiceManagedVolumeProps {
    Name = "ebs1",
    ManagedEBSVolume = new ServiceManagedEBSVolumeConfiguration {
        Size = Size.Gibibytes(15),
        VolumeType = EbsDeviceVolumeType.GP3,
        FileSystemType = FileSystemType.XFS,
        TagSpecifications = new [] { new EBSTagSpecification {
            Tags = new Dictionary<string, string> {
                { "purpose", "production" }
            },
            PropagateTags = EbsPropagatedTagSource.SERVICE
        } }
    }
});

volume.MountIn(container, new ContainerMountPoint {
    ContainerPath = "/var/lib",
    ReadOnly = false
});

taskDefinition.AddVolume(volume);

var service = new FargateService(this, "FargateService", new FargateServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    MinHealthyPercent = 100
});

service.AddVolume(volume);
go
var cluster Cluster

taskDefinition := ecs.NewFargateTaskDefinition(this, jsii.String("TaskDef"))

container := taskDefinition.AddContainer(jsii.String("web"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("amazon/amazon-ecs-sample")),
	PortMappings: []PortMapping{
		&PortMapping{
			ContainerPort: jsii.Number(80),
			Protocol: ecs.Protocol_TCP,
		},
	},
})

volume := ecs.NewServiceManagedVolume(this, jsii.String("EBSVolume"), &ServiceManagedVolumeProps{
	Name: jsii.String("ebs1"),
	ManagedEBSVolume: &ServiceManagedEBSVolumeConfiguration{
		Size: awscdk.Size_Gibibytes(jsii.Number(15)),
		VolumeType: ec2.EbsDeviceVolumeType_GP3,
		FileSystemType: ecs.FileSystemType_XFS,
		TagSpecifications: []EBSTagSpecification{
			&EBSTagSpecification{
				Tags: map[string]*string{
					"purpose": jsii.String("production"),
				},
				PropagateTags: ecs.EbsPropagatedTagSource_SERVICE,
			},
		},
	},
})

volume.MountIn(container, &ContainerMountPoint{
	ContainerPath: jsii.String("/var/lib"),
	ReadOnly: jsii.Boolean(false),
})

taskDefinition.AddVolume(volume)

service := ecs.NewFargateService(this, jsii.String("FargateService"), &FargateServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	MinHealthyPercent: jsii.Number(100),
})

service.AddVolume(volume)

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

ts
declare const container: ecs.ContainerDefinition;
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;

const volumeFromSnapshot = new ecs.ServiceManagedVolume(this, 'EBSVolume', {
  name: 'nginx-vol',
  managedEBSVolume: {
    snapShotId: 'snap-066877671789bd71b',
    volumeType: ec2.EbsDeviceVolumeType.GP3,
    fileSystemType: ecs.FileSystemType.XFS,
    // Specifies the Amazon EBS Provisioned Rate for Volume Initialization.
    // Valid range is between 100 and 300 MiB/s.
    volumeInitializationRate: Size.mebibytes(200),
  },
});

volumeFromSnapshot.mountIn(container, {
  containerPath: '/var/lib',
  readOnly: false,
});
taskDefinition.addVolume(volumeFromSnapshot);
const service = new ecs.FargateService(this, 'FargateService', {
  cluster,
  taskDefinition,
  minHealthyPercent: 100,
});

service.addVolume(volumeFromSnapshot);
python
# container: ecs.ContainerDefinition
# cluster: ecs.Cluster
# task_definition: ecs.TaskDefinition


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

volume_from_snapshot.mount_in(container,
    container_path="/var/lib",
    read_only=False
)
task_definition.add_volume(volume_from_snapshot)
service = ecs.FargateService(self, "FargateService",
    cluster=cluster,
    task_definition=task_definition,
    min_healthy_percent=100
)

service.add_volume(volume_from_snapshot)
java
ContainerDefinition container;
Cluster cluster;
TaskDefinition taskDefinition;


ServiceManagedVolume volumeFromSnapshot = ServiceManagedVolume.Builder.create(this, "EBSVolume")
        .name("nginx-vol")
        .managedEBSVolume(ServiceManagedEBSVolumeConfiguration.builder()
                .snapShotId("snap-066877671789bd71b")
                .volumeType(EbsDeviceVolumeType.GP3)
                .fileSystemType(FileSystemType.XFS)
                // Specifies the Amazon EBS Provisioned Rate for Volume Initialization.
                // Valid range is between 100 and 300 MiB/s.
                .volumeInitializationRate(Size.mebibytes(200))
                .build())
        .build();

volumeFromSnapshot.mountIn(container, ContainerMountPoint.builder()
        .containerPath("/var/lib")
        .readOnly(false)
        .build());
taskDefinition.addVolume(volumeFromSnapshot);
FargateService service = FargateService.Builder.create(this, "FargateService")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .minHealthyPercent(100)
        .build();

service.addVolume(volumeFromSnapshot);
csharp
ContainerDefinition container;
Cluster cluster;
TaskDefinition taskDefinition;


var volumeFromSnapshot = new ServiceManagedVolume(this, "EBSVolume", new ServiceManagedVolumeProps {
    Name = "nginx-vol",
    ManagedEBSVolume = new ServiceManagedEBSVolumeConfiguration {
        SnapShotId = "snap-066877671789bd71b",
        VolumeType = EbsDeviceVolumeType.GP3,
        FileSystemType = FileSystemType.XFS,
        // Specifies the Amazon EBS Provisioned Rate for Volume Initialization.
        // Valid range is between 100 and 300 MiB/s.
        VolumeInitializationRate = Size.Mebibytes(200)
    }
});

volumeFromSnapshot.MountIn(container, new ContainerMountPoint {
    ContainerPath = "/var/lib",
    ReadOnly = false
});
taskDefinition.AddVolume(volumeFromSnapshot);
var service = new FargateService(this, "FargateService", new FargateServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    MinHealthyPercent = 100
});

service.AddVolume(volumeFromSnapshot);
go
var container ContainerDefinition
var cluster Cluster
var taskDefinition TaskDefinition


volumeFromSnapshot := ecs.NewServiceManagedVolume(this, jsii.String("EBSVolume"), &ServiceManagedVolumeProps{
	Name: jsii.String("nginx-vol"),
	ManagedEBSVolume: &ServiceManagedEBSVolumeConfiguration{
		SnapShotId: jsii.String("snap-066877671789bd71b"),
		VolumeType: ec2.EbsDeviceVolumeType_GP3,
		FileSystemType: ecs.FileSystemType_XFS,
		// Specifies the Amazon EBS Provisioned Rate for Volume Initialization.
		// Valid range is between 100 and 300 MiB/s.
		VolumeInitializationRate: awscdk.Size_Mebibytes(jsii.Number(200)),
	},
})

volumeFromSnapshot.MountIn(container, &ContainerMountPoint{
	ContainerPath: jsii.String("/var/lib"),
	ReadOnly: jsii.Boolean(false),
})
taskDefinition.AddVolume(volumeFromSnapshot)
service := ecs.NewFargateService(this, jsii.String("FargateService"), &FargateServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	MinHealthyPercent: jsii.Number(100),
})

service.AddVolume(volumeFromSnapshot)

Enable pseudo-terminal (TTY) allocation ​

You can allocate a pseudo-terminal (TTY) for a container passing pseudoTerminal option while adding the container to the task definition. This maps to Tty option in the "Create a container section" of the Docker Remote API and the --tty option to docker run.

ts
const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');
taskDefinition.addContainer('TheContainer', {
  image: ecs.ContainerImage.fromRegistry('example-image'),
  pseudoTerminal: true
});
python
task_definition = ecs.Ec2TaskDefinition(self, "TaskDef")
task_definition.add_container("TheContainer",
    image=ecs.ContainerImage.from_registry("example-image"),
    pseudo_terminal=True
)
java
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("example-image"))
        .pseudoTerminal(true)
        .build());
csharp
var taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.AddContainer("TheContainer", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("example-image"),
    PseudoTerminal = true
});
go
taskDefinition := ecs.NewEc2TaskDefinition(this, jsii.String("TaskDef"))
taskDefinition.AddContainer(jsii.String("TheContainer"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("example-image")),
	PseudoTerminal: jsii.Boolean(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.

ts
const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');
taskDefinition.addContainer('TheContainer', {
  image: ecs.ContainerImage.fromRegistry('example-image'),
  versionConsistency: ecs.VersionConsistency.DISABLED,
});
python
task_definition = ecs.Ec2TaskDefinition(self, "TaskDef")
task_definition.add_container("TheContainer",
    image=ecs.ContainerImage.from_registry("example-image"),
    version_consistency=ecs.VersionConsistency.DISABLED
)
java
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("example-image"))
        .versionConsistency(VersionConsistency.DISABLED)
        .build());
csharp
var taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.AddContainer("TheContainer", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("example-image"),
    VersionConsistency = VersionConsistency.DISABLED
});
go
taskDefinition := ecs.NewEc2TaskDefinition(this, jsii.String("TaskDef"))
taskDefinition.AddContainer(jsii.String("TheContainer"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("example-image")),
	VersionConsistency: 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.

ts
const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');
taskDefinition.addContainer('TheContainer', {
  image: ecs.ContainerImage.fromRegistry('example-image'),
  ulimits: [{
    hardLimit: 128,
    name: ecs.UlimitName.RSS,
    softLimit: 128,
  }],
});
python
task_definition = ecs.Ec2TaskDefinition(self, "TaskDef")
task_definition.add_container("TheContainer",
    image=ecs.ContainerImage.from_registry("example-image"),
    ulimits=[ecs.Ulimit(
        hard_limit=128,
        name=ecs.UlimitName.RSS,
        soft_limit=128
    )]
)
java
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
        .image(ContainerImage.fromRegistry("example-image"))
        .ulimits(List.of(Ulimit.builder()
                .hardLimit(128)
                .name(UlimitName.RSS)
                .softLimit(128)
                .build()))
        .build());
csharp
var taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.AddContainer("TheContainer", new ContainerDefinitionOptions {
    Image = ContainerImage.FromRegistry("example-image"),
    Ulimits = new [] { new Ulimit {
        HardLimit = 128,
        Name = UlimitName.RSS,
        SoftLimit = 128
    } }
});
go
taskDefinition := ecs.NewEc2TaskDefinition(this, jsii.String("TaskDef"))
taskDefinition.AddContainer(jsii.String("TheContainer"), &ContainerDefinitionOptions{
	Image: ecs.ContainerImage_FromRegistry(jsii.String("example-image")),
	Ulimits: []Ulimit{
		&Ulimit{
			HardLimit: jsii.Number(128),
			Name: ecs.UlimitName_RSS,
			SoftLimit: jsii.Number(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 serviceConnectConfiguration property.

The tls property is an object with the following properties:

  • role: The IAM role that's associated with the Service Connect TLS.
  • awsPcaAuthorityArn: The ARN of the certificate root authority that secures your service.
  • kmsKey: The KMS key used for encryption and decryption.
ts
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;
declare const kmsKey: kms.IKey;
declare const role: iam.IRole;

const service = new ecs.FargateService(this, 'FargateService', {
  cluster,
  taskDefinition,
  serviceConnectConfiguration: {
    services: [
      {
        tls: {
          role,
          kmsKey,
          awsPcaAuthorityArn: 'arn:aws:acm-pca:us-east-1:123456789012:certificate-authority/123456789012',
        },
        portMappingName: 'api',
      },
    ],
    namespace: 'sample namespace',
  },
});
python
# cluster: ecs.Cluster
# task_definition: ecs.TaskDefinition
# kms_key: kms.IKey
# role: iam.IRole


service = ecs.FargateService(self, "FargateService",
    cluster=cluster,
    task_definition=task_definition,
    service_connect_configuration=ecs.ServiceConnectProps(
        services=[ecs.ServiceConnectService(
            tls=ecs.ServiceConnectTlsConfiguration(
                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"
    )
)
java
Cluster cluster;
TaskDefinition taskDefinition;
IKey kmsKey;
IRole role;


FargateService service = FargateService.Builder.create(this, "FargateService")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .serviceConnectConfiguration(ServiceConnectProps.builder()
                .services(List.of(ServiceConnectService.builder()
                        .tls(ServiceConnectTlsConfiguration.builder()
                                .role(role)
                                .kmsKey(kmsKey)
                                .awsPcaAuthorityArn("arn:aws:acm-pca:us-east-1:123456789012:certificate-authority/123456789012")
                                .build())
                        .portMappingName("api")
                        .build()))
                .namespace("sample namespace")
                .build())
        .build();
csharp
Cluster cluster;
TaskDefinition taskDefinition;
IKey kmsKey;
IRole role;


var service = new FargateService(this, "FargateService", new FargateServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    ServiceConnectConfiguration = new ServiceConnectProps {
        Services = new [] { new ServiceConnectService {
            Tls = new ServiceConnectTlsConfiguration {
                Role = role,
                KmsKey = kmsKey,
                AwsPcaAuthorityArn = "arn:aws:acm-pca:us-east-1:123456789012:certificate-authority/123456789012"
            },
            PortMappingName = "api"
        } },
        Namespace = "sample namespace"
    }
});
go
var cluster Cluster
var taskDefinition TaskDefinition
var kmsKey IKey
var role IRole


service := ecs.NewFargateService(this, jsii.String("FargateService"), &FargateServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	ServiceConnectConfiguration: &ServiceConnectProps{
		Services: []ServiceConnectService{
			&ServiceConnectService{
				Tls: &ServiceConnectTlsConfiguration{
					Role: *Role,
					KmsKey: *KmsKey,
					AwsPcaAuthorityArn: jsii.String("arn:aws:acm-pca:us-east-1:123456789012:certificate-authority/123456789012"),
				},
				PortMappingName: jsii.String("api"),
			},
		},
		Namespace: jsii.String("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

ts
import * as lambda from 'aws-cdk-lib/aws-lambda';

declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;
declare const lambdaHook: lambda.Function;
declare const blueTargetGroup: elbv2.ApplicationTargetGroup;
declare const greenTargetGroup: elbv2.ApplicationTargetGroup;
declare const prodListenerRule: elbv2.ApplicationListenerRule;

const service = new ecs.FargateService(this, 'Service', {
  cluster,
  taskDefinition,
  deploymentStrategy: ecs.DeploymentStrategy.BLUE_GREEN,
});

service.addLifecycleHook(new ecs.DeploymentLifecycleLambdaTarget(lambdaHook, 'PreScaleHook', {
  lifecycleStages: [ecs.DeploymentLifecycleStage.PRE_SCALE_UP],
}));

const target = service.loadBalancerTarget({
  containerName: 'nginx',
  containerPort: 80,
  protocol: ecs.Protocol.TCP,
  alternateTarget: new ecs.AlternateTarget('AlternateTarget', {
    alternateTargetGroup: greenTargetGroup,
    productionListener: ecs.ListenerRuleConfiguration.applicationListenerRule(prodListenerRule),
  }),
});

target.attachToApplicationTargetGroup(blueTargetGroup);
python
import aws_cdk.aws_lambda as lambda_

# cluster: ecs.Cluster
# task_definition: ecs.TaskDefinition
# lambda_hook: lambda.Function
# blue_target_group: elbv2.ApplicationTargetGroup
# green_target_group: elbv2.ApplicationTargetGroup
# prod_listener_rule: elbv2.ApplicationListenerRule


service = ecs.FargateService(self, "Service",
    cluster=cluster,
    task_definition=task_definition,
    deployment_strategy=ecs.DeploymentStrategy.BLUE_GREEN
)

service.add_lifecycle_hook(ecs.DeploymentLifecycleLambdaTarget(lambda_hook, "PreScaleHook",
    lifecycle_stages=[ecs.DeploymentLifecycleStage.PRE_SCALE_UP]
))

target = service.load_balancer_target(
    container_name="nginx",
    container_port=80,
    protocol=ecs.Protocol.TCP,
    alternate_target=ecs.AlternateTarget("AlternateTarget",
        alternate_target_group=green_target_group,
        production_listener=ecs.ListenerRuleConfiguration.application_listener_rule(prod_listener_rule)
    )
)

target.attach_to_application_target_group(blue_target_group)
java
import software.amazon.awscdk.services.lambda.*;

Cluster cluster;
TaskDefinition taskDefinition;
Function lambdaHook;
ApplicationTargetGroup blueTargetGroup;
ApplicationTargetGroup greenTargetGroup;
ApplicationListenerRule prodListenerRule;


FargateService service = FargateService.Builder.create(this, "Service")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .deploymentStrategy(DeploymentStrategy.BLUE_GREEN)
        .build();

service.addLifecycleHook(DeploymentLifecycleLambdaTarget.Builder.create(lambdaHook, "PreScaleHook")
        .lifecycleStages(List.of(DeploymentLifecycleStage.PRE_SCALE_UP))
        .build());

IEcsLoadBalancerTarget target = service.loadBalancerTarget(LoadBalancerTargetOptions.builder()
        .containerName("nginx")
        .containerPort(80)
        .protocol(Protocol.TCP)
        .alternateTarget(AlternateTarget.Builder.create("AlternateTarget")
                .alternateTargetGroup(greenTargetGroup)
                .productionListener(ListenerRuleConfiguration.applicationListenerRule(prodListenerRule))
                .build())
        .build());

target.attachToApplicationTargetGroup(blueTargetGroup);
csharp
using Amazon.CDK.AWS.Lambda;

Cluster cluster;
TaskDefinition taskDefinition;
Function lambdaHook;
ApplicationTargetGroup blueTargetGroup;
ApplicationTargetGroup greenTargetGroup;
ApplicationListenerRule prodListenerRule;


var service = new FargateService(this, "Service", new FargateServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    DeploymentStrategy = DeploymentStrategy.BLUE_GREEN
});

service.AddLifecycleHook(new DeploymentLifecycleLambdaTarget(lambdaHook, "PreScaleHook", new DeploymentLifecycleLambdaTargetProps {
    LifecycleStages = new [] { DeploymentLifecycleStage.PRE_SCALE_UP }
}));

var target = service.LoadBalancerTarget(new LoadBalancerTargetOptions {
    ContainerName = "nginx",
    ContainerPort = 80,
    Protocol = Protocol.TCP,
    AlternateTarget = new AlternateTarget("AlternateTarget", new AlternateTargetProps {
        AlternateTargetGroup = greenTargetGroup,
        ProductionListener = ListenerRuleConfiguration.ApplicationListenerRule(prodListenerRule)
    })
});

target.AttachToApplicationTargetGroup(blueTargetGroup);
go
import lambda "github.com/aws/aws-cdk-go/awscdk"

var cluster Cluster
var taskDefinition TaskDefinition
var lambdaHook Function
var blueTargetGroup ApplicationTargetGroup
var greenTargetGroup ApplicationTargetGroup
var prodListenerRule ApplicationListenerRule


service := ecs.NewFargateService(this, jsii.String("Service"), &FargateServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	DeploymentStrategy: ecs.DeploymentStrategy_BLUE_GREEN,
})

service.AddLifecycleHook(ecs.NewDeploymentLifecycleLambdaTarget(lambdaHook, jsii.String("PreScaleHook"), &DeploymentLifecycleLambdaTargetProps{
	LifecycleStages: []DeploymentLifecycleStage{
		ecs.DeploymentLifecycleStage_PRE_SCALE_UP,
	},
}))

target := service.LoadBalancerTarget(&LoadBalancerTargetOptions{
	ContainerName: jsii.String("nginx"),
	ContainerPort: jsii.Number(80),
	Protocol: ecs.Protocol_TCP,
	AlternateTarget: ecs.NewAlternateTarget(jsii.String("AlternateTarget"), &AlternateTargetProps{
		AlternateTargetGroup: greenTargetGroup,
		ProductionListener: ecs.ListenerRuleConfiguration_ApplicationListenerRule(prodListenerRule),
	}),
})

target.AttachToApplicationTargetGroup(blueTargetGroup)

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:

ts
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;
declare const blueTargetGroup: elbv2.ApplicationTargetGroup;
declare const greenTargetGroup: elbv2.ApplicationTargetGroup;
declare const prodListenerRule: elbv2.ApplicationListenerRule;

const service = new ecs.FargateService(this, 'Service', {
  cluster,
  taskDefinition,
  deploymentStrategy: ecs.DeploymentStrategy.LINEAR,
  linearConfiguration: {
    stepPercent: 10.0,
    stepBakeTime: Duration.minutes(5),
  },
});

const target = service.loadBalancerTarget({
  containerName: 'web',
  containerPort: 80,
  alternateTarget: new ecs.AlternateTarget('AlternateTarget', {
    alternateTargetGroup: greenTargetGroup,
    productionListener: ecs.ListenerRuleConfiguration.applicationListenerRule(prodListenerRule),
  }),
});

target.attachToApplicationTargetGroup(blueTargetGroup);
python
# cluster: ecs.Cluster
# task_definition: ecs.TaskDefinition
# blue_target_group: elbv2.ApplicationTargetGroup
# green_target_group: elbv2.ApplicationTargetGroup
# prod_listener_rule: elbv2.ApplicationListenerRule


service = ecs.FargateService(self, "Service",
    cluster=cluster,
    task_definition=task_definition,
    deployment_strategy=ecs.DeploymentStrategy.LINEAR,
    linear_configuration=ecs.TrafficShiftConfig(
        step_percent=10,
        step_bake_time=Duration.minutes(5)
    )
)

target = service.load_balancer_target(
    container_name="web",
    container_port=80,
    alternate_target=ecs.AlternateTarget("AlternateTarget",
        alternate_target_group=green_target_group,
        production_listener=ecs.ListenerRuleConfiguration.application_listener_rule(prod_listener_rule)
    )
)

target.attach_to_application_target_group(blue_target_group)
java
Cluster cluster;
TaskDefinition taskDefinition;
ApplicationTargetGroup blueTargetGroup;
ApplicationTargetGroup greenTargetGroup;
ApplicationListenerRule prodListenerRule;


FargateService service = FargateService.Builder.create(this, "Service")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .deploymentStrategy(DeploymentStrategy.LINEAR)
        .linearConfiguration(TrafficShiftConfig.builder()
                .stepPercent(10)
                .stepBakeTime(Duration.minutes(5))
                .build())
        .build();

IEcsLoadBalancerTarget target = service.loadBalancerTarget(LoadBalancerTargetOptions.builder()
        .containerName("web")
        .containerPort(80)
        .alternateTarget(AlternateTarget.Builder.create("AlternateTarget")
                .alternateTargetGroup(greenTargetGroup)
                .productionListener(ListenerRuleConfiguration.applicationListenerRule(prodListenerRule))
                .build())
        .build());

target.attachToApplicationTargetGroup(blueTargetGroup);
csharp
Cluster cluster;
TaskDefinition taskDefinition;
ApplicationTargetGroup blueTargetGroup;
ApplicationTargetGroup greenTargetGroup;
ApplicationListenerRule prodListenerRule;


var service = new FargateService(this, "Service", new FargateServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    DeploymentStrategy = DeploymentStrategy.LINEAR,
    LinearConfiguration = new TrafficShiftConfig {
        StepPercent = 10,
        StepBakeTime = Duration.Minutes(5)
    }
});

var target = service.LoadBalancerTarget(new LoadBalancerTargetOptions {
    ContainerName = "web",
    ContainerPort = 80,
    AlternateTarget = new AlternateTarget("AlternateTarget", new AlternateTargetProps {
        AlternateTargetGroup = greenTargetGroup,
        ProductionListener = ListenerRuleConfiguration.ApplicationListenerRule(prodListenerRule)
    })
});

target.AttachToApplicationTargetGroup(blueTargetGroup);
go
var cluster Cluster
var taskDefinition TaskDefinition
var blueTargetGroup ApplicationTargetGroup
var greenTargetGroup ApplicationTargetGroup
var prodListenerRule ApplicationListenerRule


service := ecs.NewFargateService(this, jsii.String("Service"), &FargateServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	DeploymentStrategy: ecs.DeploymentStrategy_LINEAR,
	LinearConfiguration: &TrafficShiftConfig{
		StepPercent: jsii.Number(10),
		StepBakeTime: awscdk.Duration_Minutes(jsii.Number(5)),
	},
})

target := service.LoadBalancerTarget(&LoadBalancerTargetOptions{
	ContainerName: jsii.String("web"),
	ContainerPort: jsii.Number(80),
	AlternateTarget: ecs.NewAlternateTarget(jsii.String("AlternateTarget"), &AlternateTargetProps{
		AlternateTargetGroup: greenTargetGroup,
		ProductionListener: ecs.ListenerRuleConfiguration_ApplicationListenerRule(prodListenerRule),
	}),
})

target.AttachToApplicationTargetGroup(blueTargetGroup)

Valid values:

  • stepPercent: 3.0 to 100.0 (multiples of 0.1). Default: 10.0
  • stepBakeTime: 0 to 1440 minutes (24 hours). Default: 6 minutes

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:

ts
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;
declare const blueTargetGroup: elbv2.ApplicationTargetGroup;
declare const greenTargetGroup: elbv2.ApplicationTargetGroup;
declare const prodListenerRule: elbv2.ApplicationListenerRule;

const service = new ecs.FargateService(this, 'Service', {
  cluster,
  taskDefinition,
  deploymentStrategy: ecs.DeploymentStrategy.CANARY,
  canaryConfiguration: {
    stepPercent: 5.0,
    stepBakeTime: Duration.minutes(10),
  },
});

const target = service.loadBalancerTarget({
  containerName: 'web',
  containerPort: 80,
  alternateTarget: new ecs.AlternateTarget('AlternateTarget', {
    alternateTargetGroup: greenTargetGroup,
    productionListener: ecs.ListenerRuleConfiguration.applicationListenerRule(prodListenerRule),
  }),
});

target.attachToApplicationTargetGroup(blueTargetGroup);
python
# cluster: ecs.Cluster
# task_definition: ecs.TaskDefinition
# blue_target_group: elbv2.ApplicationTargetGroup
# green_target_group: elbv2.ApplicationTargetGroup
# prod_listener_rule: elbv2.ApplicationListenerRule


service = ecs.FargateService(self, "Service",
    cluster=cluster,
    task_definition=task_definition,
    deployment_strategy=ecs.DeploymentStrategy.CANARY,
    canary_configuration=ecs.TrafficShiftConfig(
        step_percent=5,
        step_bake_time=Duration.minutes(10)
    )
)

target = service.load_balancer_target(
    container_name="web",
    container_port=80,
    alternate_target=ecs.AlternateTarget("AlternateTarget",
        alternate_target_group=green_target_group,
        production_listener=ecs.ListenerRuleConfiguration.application_listener_rule(prod_listener_rule)
    )
)

target.attach_to_application_target_group(blue_target_group)
java
Cluster cluster;
TaskDefinition taskDefinition;
ApplicationTargetGroup blueTargetGroup;
ApplicationTargetGroup greenTargetGroup;
ApplicationListenerRule prodListenerRule;


FargateService service = FargateService.Builder.create(this, "Service")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .deploymentStrategy(DeploymentStrategy.CANARY)
        .canaryConfiguration(TrafficShiftConfig.builder()
                .stepPercent(5)
                .stepBakeTime(Duration.minutes(10))
                .build())
        .build();

IEcsLoadBalancerTarget target = service.loadBalancerTarget(LoadBalancerTargetOptions.builder()
        .containerName("web")
        .containerPort(80)
        .alternateTarget(AlternateTarget.Builder.create("AlternateTarget")
                .alternateTargetGroup(greenTargetGroup)
                .productionListener(ListenerRuleConfiguration.applicationListenerRule(prodListenerRule))
                .build())
        .build());

target.attachToApplicationTargetGroup(blueTargetGroup);
csharp
Cluster cluster;
TaskDefinition taskDefinition;
ApplicationTargetGroup blueTargetGroup;
ApplicationTargetGroup greenTargetGroup;
ApplicationListenerRule prodListenerRule;


var service = new FargateService(this, "Service", new FargateServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    DeploymentStrategy = DeploymentStrategy.CANARY,
    CanaryConfiguration = new TrafficShiftConfig {
        StepPercent = 5,
        StepBakeTime = Duration.Minutes(10)
    }
});

var target = service.LoadBalancerTarget(new LoadBalancerTargetOptions {
    ContainerName = "web",
    ContainerPort = 80,
    AlternateTarget = new AlternateTarget("AlternateTarget", new AlternateTargetProps {
        AlternateTargetGroup = greenTargetGroup,
        ProductionListener = ListenerRuleConfiguration.ApplicationListenerRule(prodListenerRule)
    })
});

target.AttachToApplicationTargetGroup(blueTargetGroup);
go
var cluster Cluster
var taskDefinition TaskDefinition
var blueTargetGroup ApplicationTargetGroup
var greenTargetGroup ApplicationTargetGroup
var prodListenerRule ApplicationListenerRule


service := ecs.NewFargateService(this, jsii.String("Service"), &FargateServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	DeploymentStrategy: ecs.DeploymentStrategy_CANARY,
	CanaryConfiguration: &TrafficShiftConfig{
		StepPercent: jsii.Number(5),
		StepBakeTime: awscdk.Duration_Minutes(jsii.Number(10)),
	},
})

target := service.LoadBalancerTarget(&LoadBalancerTargetOptions{
	ContainerName: jsii.String("web"),
	ContainerPort: jsii.Number(80),
	AlternateTarget: ecs.NewAlternateTarget(jsii.String("AlternateTarget"), &AlternateTargetProps{
		AlternateTargetGroup: greenTargetGroup,
		ProductionListener: ecs.ListenerRuleConfiguration_ApplicationListenerRule(prodListenerRule),
	}),
})

target.AttachToApplicationTargetGroup(blueTargetGroup)

Valid values:

  • stepPercent: 0.1 to 100.0 (multiples of 0.1). Default: 5.0
  • stepBakeTime: 0 to 1440 minutes (24 hours). Default: 10 minutes

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

ts
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;

new ecs.Ec2Service(this, 'Ec2Service', {
  cluster,
  taskDefinition,
  daemon: true,
});

new ecs.ExternalService(this, 'ExternalService', {
  cluster,
  taskDefinition,
  daemon: true,
});
python
# cluster: ecs.Cluster
# task_definition: ecs.TaskDefinition


ecs.Ec2Service(self, "Ec2Service",
    cluster=cluster,
    task_definition=task_definition,
    daemon=True
)

ecs.ExternalService(self, "ExternalService",
    cluster=cluster,
    task_definition=task_definition,
    daemon=True
)
java
Cluster cluster;
TaskDefinition taskDefinition;


Ec2Service.Builder.create(this, "Ec2Service")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .daemon(true)
        .build();

ExternalService.Builder.create(this, "ExternalService")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .daemon(true)
        .build();
csharp
Cluster cluster;
TaskDefinition taskDefinition;


new Ec2Service(this, "Ec2Service", new Ec2ServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    Daemon = true
});

new ExternalService(this, "ExternalService", new ExternalServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    Daemon = true
});
go
var cluster Cluster
var taskDefinition TaskDefinition


ecs.NewEc2Service(this, jsii.String("Ec2Service"), &Ec2ServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	Daemon: jsii.Boolean(true),
})

ecs.NewExternalService(this, jsii.String("ExternalService"), &ExternalServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	Daemon: jsii.Boolean(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).

ts
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;

const service = new ecs.FargateService(this, 'Service', {
  cluster,
  taskDefinition,
});

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

// Or provide your own nonce to control when deployments are triggered
service.forceNewDeployment('my-custom-nonce-v2');
python
# cluster: ecs.Cluster
# task_definition: ecs.TaskDefinition


service = ecs.FargateService(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")
java
Cluster cluster;
TaskDefinition taskDefinition;


FargateService service = FargateService.Builder.create(this, "Service")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .build();

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

// Or provide your own nonce to control when deployments are triggered
service.forceNewDeployment("my-custom-nonce-v2");
csharp
Cluster cluster;
TaskDefinition taskDefinition;


var service = new FargateService(this, "Service", new FargateServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition
});

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

// Or provide your own nonce to control when deployments are triggered
service.ForceNewDeployment("my-custom-nonce-v2");
go
var cluster Cluster
var taskDefinition TaskDefinition


service := ecs.NewFargateService(this, jsii.String("Service"), &FargateServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
})

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

// Or provide your own nonce to control when deployments are triggered
service.ForceNewDeployment(jsii.String("my-custom-nonce-v2"))

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

ts
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;

// Force a new deployment on every `cdk deploy` by using a time-based nonce
const service = new ecs.FargateService(this, 'Service', {
  cluster,
  taskDefinition,
  forceNewDeployment: {
    enabled: true,
    nonce: Date.now().toString(),
  },
});
python
# cluster: ecs.Cluster
# task_definition: ecs.TaskDefinition


# Force a new deployment on every `cdk deploy` by using a time-based nonce
service = ecs.FargateService(self, "Service",
    cluster=cluster,
    task_definition=task_definition,
    force_new_deployment=ecs.ForceNewDeployment(
        enabled=True,
        nonce=Date.now().to_string()
    )
)
java
Cluster cluster;
TaskDefinition taskDefinition;


// Force a new deployment on every `cdk deploy` by using a time-based nonce
FargateService service = FargateService.Builder.create(this, "Service")
        .cluster(cluster)
        .taskDefinition(taskDefinition)
        .forceNewDeployment(ForceNewDeployment.builder()
                .enabled(true)
                .nonce(Date.now().toString())
                .build())
        .build();
csharp
Cluster cluster;
TaskDefinition taskDefinition;


// Force a new deployment on every `cdk deploy` by using a time-based nonce
var service = new FargateService(this, "Service", new FargateServiceProps {
    Cluster = cluster,
    TaskDefinition = taskDefinition,
    ForceNewDeployment = new ForceNewDeployment {
        Enabled = true,
        Nonce = Date.Now().ToString()
    }
});
go
var cluster Cluster
var taskDefinition TaskDefinition


// Force a new deployment on every `cdk deploy` by using a time-based nonce
service := ecs.NewFargateService(this, jsii.String("Service"), &FargateServiceProps{
	Cluster: Cluster,
	TaskDefinition: TaskDefinition,
	ForceNewDeployment: &ForceNewDeployment{
		Enabled: jsii.Boolean(true),
		Nonce: date.now().toString(),
	},
})

Calling the forceNewDeployment() 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 forceNewDeployment 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:

ts
new ecs.CfnCluster(this, 'Cluster')
  .with(new ecs.mixins.ClusterSettings([{ name: 'containerInsights', value: 'enhanced' }]));
python
ecs.CfnCluster(self, "Cluster").with(ecs.mixins.ClusterSettings([name="containerInsights", value="enhanced"]))
java
new CfnCluster(this, "Cluster").with(new ClusterSettings(List.of(ClusterSettingsProperty.builder().name("containerInsights").value("enhanced").build())));
csharp
new CfnCluster(this, "Cluster").With(new Mixins.ClusterSettings(new [] { new ClusterSettingsProperty { Name = "containerInsights", Value = "enhanced" } }));
go
ecs.NewCfnCluster(this, jsii.String("Cluster")).With(mixins.NewClusterSettings([]ClusterSettingsProperty{
	&ClusterSettingsProperty{
		Name: jsii.String("containerInsights"),
		Value: jsii.String("enhanced"),
	},
}))

Types ​

NameKindSummary
BaseServiceConstruct (L2)The base class for Ec2Service and FargateService services.
ClusterConstruct (L2)A regional grouping of one or more container instances on which you can run tasks and services.
Ec2ServiceConstruct (L2)This creates a service using the EC2 launch type on an ECS cluster.
Ec2TaskDefinitionConstruct (L2)The details of a task definition run on an EC2 cluster.
ExternalServiceConstruct (L2)This creates a service using the External launch type on an ECS cluster.
ExternalTaskDefinitionConstruct (L2)The details of a task definition run on an External cluster.
FargateServiceConstruct (L2)This creates a service using the Fargate launch type on an ECS cluster.
FargateTaskDefinitionConstruct (L2)The details of a task definition run on a Fargate cluster.
TaskDefinitionConstruct (L2)The base class for all task definitions.
CfnCapacityProviderConstruct (L1)Creates a capacity provider.
CfnClusterConstruct (L1)The AWS::ECS::Cluster resource creates an Amazon Elastic Container Service (Amazon ECS) cluster.
CfnClusterCapacityProviderAssociationsConstruct (L1)The AWS::ECS::ClusterCapacityProviderAssociations resource associates one or more capacity providers and a default capacity provider strategy with a cluster.
CfnDaemonConstruct (L1)Information about a daemon resource.
CfnDaemonTaskDefinitionConstruct (L1)The details of a daemon task definition.
CfnExpressGatewayServiceConstruct (L1)Creates an Express service that simplifies deploying containerized web applications on Amazon ECS with managed AWS infrastructure.
CfnPrimaryTaskSetConstruct (L1)Modifies which task set in a service is the primary task set.
CfnServiceConstruct (L1)The AWS::ECS::Service resource creates an Amazon Elastic Container Service (Amazon ECS) service that runs and maintains the requested number of tasks and associated load balancers.
CfnTaskDefinitionConstruct (L1)Registers a new task definition from the supplied family and containerDefinitions .
CfnTaskSetConstruct (L1)Create a task set in the specified cluster and service.
AddAutoScalingGroupCapacityOptionsStructThe properties for adding an AutoScalingGroup.
AddCapacityOptionsStructThe properties for adding instance capacity to an AutoScalingGroup.
AlarmBehaviorEnumDeployment behavior when an ECS Service Deployment Alarm is triggered.
AlternateTargetClassConfiguration for alternate target groups used in blue/green deployments with load balancers.
AlternateTargetConfigStructConfiguration returned by AlternateTargetConfiguration.bind().
AlternateTargetOptionsStructOptions for AlternateTarget configuration.
AlternateTargetPropsStructProperties for AlternateTarget configuration.
AmiHardwareTypeEnumThe ECS-optimized AMI variant to use.
AppMeshProxyConfigurationClassThe class for App Mesh proxy configurations.
AppMeshProxyConfigurationConfigPropsStructThe configuration to use when setting an App Mesh proxy configuration.
AppMeshProxyConfigurationPropsStructInterface for setting the properties of proxy configuration.
AppProtocolClassService connect app protocol.
AsgCapacityProviderConstructAn Auto Scaling Group Capacity Provider.
AsgCapacityProviderPropsStructThe options for creating an Auto Scaling Group Capacity Provider.
AssetEnvironmentFileClassEnvironment file from a local directory.
AssetImageClassAn image that will be built from a local directory with a Dockerfile.
AssetImagePropsStructThe properties for building an AssetImage.
AssociateCloudMapServiceOptionsStructThe options for using a cloudmap service.
AuthorizationConfigStructThe authorization configuration details for the Amazon EFS file system.
AvailabilityZoneRebalancingEnumIndicates whether to use Availability Zone rebalancing for an ECS service.
AwsLogDriverClassA log driver that sends log information to CloudWatch Logs.
AwsLogDriverModeEnumawslogs provides two modes for delivering messages from the container to the log driver.
AwsLogDriverPropsStructSpecifies the awslogs log driver configuration options.
BaseLogDriverPropsStruct
BaseMountPointStructThe base details of where a volume will be mounted within a container.
BaseServiceOptionsStructThe properties for the base Ec2Service or FargateService service.
BaseServicePropsStructComplete base service properties that are required to be supplied by the implementation of the BaseService class.
BinPackResourceEnumInstance resource used for bin packing.
BottlerocketEcsVariantEnumAmazon ECS variant.
BottleRocketImageClassConstruct an Bottlerocket image from the latest AMI published in SSM.
BottleRocketImagePropsStructProperties for BottleRocketImage.
BuiltInAttributesClassThe built-in container instance attributes.
CapabilityEnumA Linux capability.
CapacityOptionTypeEnumThe capacity option type for instances launched by a Managed Instances Capacity Provider.
CapacityProviderStrategyStructA Capacity Provider strategy to use for the service.
CfnCapacityProvider.AcceleratorCountRequestPropertyStructThe minimum and maximum number of accelerators (such as GPUs) for instance type selection.
CfnCapacityProvider.AcceleratorTotalMemoryMiBRequestPropertyStructThe minimum and maximum total accelerator memory in mebibytes (MiB) for instance type selection.
CfnCapacityProvider.AutoRepairConfigurationPropertyStruct
CfnCapacityProvider.AutoScalingGroupProviderPropertyStructThe details of the Auto Scaling group for the capacity provider.
CfnCapacityProvider.BaselineEbsBandwidthMbpsRequestPropertyStructThe minimum and maximum baseline Amazon EBS bandwidth in megabits per second (Mbps) for instance type selection.
CfnCapacityProvider.CapacityReservationRequestPropertyStruct
CfnCapacityProvider.InfrastructureOptimizationPropertyStructThe configuration that controls how Amazon ECS optimizes your infrastructure.
CfnCapacityProvider.InstanceLaunchTemplatePropertyStructThe launch template configuration for Amazon ECS Managed Instances.
CfnCapacityProvider.InstanceRequirementsRequestPropertyStructThe instance requirements for attribute-based instance type selection.
CfnCapacityProvider.ManagedInstancesLocalStorageConfigurationPropertyStruct
CfnCapacityProvider.ManagedInstancesNetworkConfigurationPropertyStructThe network configuration for Amazon ECS Managed Instances.
CfnCapacityProvider.ManagedInstancesProviderPropertyStructThe configuration for a Amazon ECS Managed Instances provider.
CfnCapacityProvider.ManagedInstancesStorageConfigurationPropertyStructThe storage configuration for Amazon ECS Managed Instances.
CfnCapacityProvider.ManagedScalingPropertyStructThe managed scaling settings for the Auto Scaling group capacity provider.
CfnCapacityProvider.MemoryGiBPerVCpuRequestPropertyStructThe minimum and maximum amount of memory per vCPU in gibibytes (GiB).
CfnCapacityProvider.MemoryMiBRequestPropertyStructThe minimum and maximum amount of memory in mebibytes (MiB) for instance type selection.
CfnCapacityProvider.NetworkBandwidthGbpsRequestPropertyStructThe minimum and maximum network bandwidth in gigabits per second (Gbps) for instance type selection.
CfnCapacityProvider.NetworkInterfaceCountRequestPropertyStructThe minimum and maximum number of network interfaces for instance type selection.
CfnCapacityProvider.TotalLocalStorageGBRequestPropertyStructThe minimum and maximum total local storage in gigabytes (GB) for instance types with local storage.
CfnCapacityProvider.VCpuCountRangeRequestPropertyStructThe minimum and maximum number of vCPUs for instance type selection.
CfnCapacityProviderPropsStructProperties for defining a CfnCapacityProvider.
CfnCluster.CapacityProviderStrategyItemPropertyStructThe CapacityProviderStrategyItem property specifies the details of the default capacity provider strategy for the cluster.
CfnCluster.ClusterConfigurationPropertyStructThe execute command and managed storage configuration for the cluster.
CfnCluster.ClusterSettingsPropertyStructThe settings to use when creating a cluster.
CfnCluster.ExecuteCommandConfigurationPropertyStructThe details of the execute command configuration.
CfnCluster.ExecuteCommandLogConfigurationPropertyStructThe log configuration for the results of the execute command actions.
CfnCluster.ManagedStorageConfigurationPropertyStructThe managed storage configuration for the cluster.
CfnCluster.ServiceConnectDefaultsPropertyStructUse this parameter to set a default Service Connect namespace.
CfnClusterCapacityProviderAssociations.CapacityProviderStrategyPropertyStructThe CapacityProviderStrategy property specifies the details of the default capacity provider strategy for the cluster.
CfnClusterCapacityProviderAssociationsPropsStructProperties for defining a CfnClusterCapacityProviderAssociations.
CfnClusterPropsStructProperties for defining a CfnCluster.
CfnDaemon.DaemonAlarmConfigurationPropertyStructThe CloudWatch alarm configuration for a daemon.
CfnDaemon.DaemonDeploymentConfigurationPropertyStructOptional deployment parameters that control how a daemon rolls out updates across container instances.
CfnDaemonPropsStructProperties for defining a CfnDaemon.
CfnDaemonTaskDefinition.ContainerDependencyPropertyStructThe dependencies defined for container startup and shutdown.
CfnDaemonTaskDefinition.DaemonContainerDefinitionPropertyStructA container definition for a daemon task.
CfnDaemonTaskDefinition.DevicePropertyStructAn object representing a container instance host device.
CfnDaemonTaskDefinition.EnvironmentFilePropertyStructA list of files containing the environment variables to pass to a container.
CfnDaemonTaskDefinition.FirelensConfigurationPropertyStructThe FireLens configuration for the container.
CfnDaemonTaskDefinition.HealthCheckPropertyStructAn object representing a container health check.
CfnDaemonTaskDefinition.HostVolumePropertiesPropertyStructDetails on a container instance bind mount host volume.
CfnDaemonTaskDefinition.KernelCapabilitiesPropertyStructThe Linux capabilities to add or remove from the default Docker configuration for a container defined in the task definition.
CfnDaemonTaskDefinition.KeyValuePairPropertyStructA key-value pair object.
CfnDaemonTaskDefinition.LinuxParametersPropertyStructThe Linux-specific options that are applied to the container, such as Linux KernelCapabilities.
CfnDaemonTaskDefinition.LogConfigurationPropertyStructThe log configuration for the container.
CfnDaemonTaskDefinition.MountPointPropertyStructThe details for a volume mount point that's used in a container definition.
CfnDaemonTaskDefinition.RepositoryCredentialsPropertyStructThe repository credentials for private registry authentication.
CfnDaemonTaskDefinition.RestartPolicyPropertyStruct
CfnDaemonTaskDefinition.SecretPropertyStructAn object representing the secret to expose to your container.
CfnDaemonTaskDefinition.SystemControlPropertyStructA list of namespaced kernel parameters to set in the container.
CfnDaemonTaskDefinition.TmpfsPropertyStructThe container path, mount options, and size of the tmpfs mount.
CfnDaemonTaskDefinition.UlimitPropertyStructThe ulimit settings to pass to the container.
CfnDaemonTaskDefinition.VolumePropertyStructThe data volume configuration for tasks launched using this task definition.
CfnDaemonTaskDefinitionPropsStructProperties for defining a CfnDaemonTaskDefinition.
CfnExpressGatewayService.AutoScalingArnsPropertyStruct
CfnExpressGatewayService.ECSManagedResourceArnsPropertyStruct
CfnExpressGatewayService.ExpressGatewayContainerPropertyStructDefines the configuration for the primary container in an Express service.
CfnExpressGatewayService.ExpressGatewayRepositoryCredentialsPropertyStructThe repository credentials for private registry authentication to pass to the container.
CfnExpressGatewayService.ExpressGatewayScalingTargetPropertyStructDefines the auto-scaling configuration for an Express service.
CfnExpressGatewayService.ExpressGatewayServiceAwsLogsConfigurationPropertyStructSpecifies the Amazon CloudWatch Logs configuration for the Express service container.
CfnExpressGatewayService.ExpressGatewayServiceConfigurationPropertyStructRepresents a specific configuration revision of an Express service, containing all the settings and parameters for that revision.
CfnExpressGatewayService.ExpressGatewayServiceNetworkConfigurationPropertyStructThe network configuration for an Express service.
CfnExpressGatewayService.ExpressGatewayServiceStatusPropertyStructAn object that defines the status of Express service creation and information about the status of the service.
CfnExpressGatewayService.IngressPathArnsPropertyStruct
CfnExpressGatewayService.IngressPathSummaryPropertyStructThe entry point into an Express service.
CfnExpressGatewayService.KeyValuePairPropertyStructA key-value pair object.
CfnExpressGatewayService.SecretPropertyStructAn object representing the secret to expose to your container.
CfnExpressGatewayServicePropsStructProperties for defining a CfnExpressGatewayService.
CfnPrimaryTaskSetPropsStructProperties for defining a CfnPrimaryTaskSet.
CfnService.AdvancedConfigurationPropertyStructThe advanced settings for a load balancer used in blue/green deployments.
CfnService.AwsVpcConfigurationPropertyStructAn object representing the networking details for a task or service.
CfnService.CanaryConfigurationPropertyStructConfiguration for a canary deployment strategy that shifts a fixed percentage of traffic to the new service revision, waits for a specified bake time, then shifts the remaining traffic.
CfnService.CapacityProviderStrategyItemPropertyStructThe details of a capacity provider strategy.
CfnService.DeploymentAlarmsPropertyStructOne of the methods which provide a way for you to quickly identify when a deployment has failed, and then to optionally roll back the failure to the last working deployment.
CfnService.DeploymentCircuitBreakerPropertyStruct> The deployment circuit breaker can only be used for services using the rolling update ( ECS ) deployment type.
CfnService.DeploymentConfigurationPropertyStructOptional deployment parameters that control how many tasks run during a deployment and the ordering of stopping and starting tasks.
CfnService.DeploymentControllerPropertyStructThe deployment controller to use for the service.
CfnService.DeploymentEarlySuccessCriteriaPropertyStruct
CfnService.DeploymentLifecycleHookPropertyStructA deployment lifecycle hook runs custom logic at specific stages of the deployment process.
CfnService.EBSTagSpecificationPropertyStructThe tag specifications of an Amazon EBS volume.
CfnService.ForceNewDeploymentPropertyStructDetermines whether to force a new deployment of the service.
CfnService.HookTimeoutConfigPropertyStruct
CfnService.LinearConfigurationPropertyStructConfiguration for a linear deployment strategy that shifts production traffic in equal percentage increments with configurable wait times between each step until 100 percent of traffic is shifted to the new service revision.
CfnService.LoadBalancerPropertyStructThe LoadBalancer property specifies details on a load balancer that is used with a service.
CfnService.LogConfigurationPropertyStructThe log configuration for the container.
CfnService.MetricConfigurationPropertyStructThe configuration for a specific set of metrics to collect for a service.
CfnService.MonitoringConfigurationPropertyStructThe optional monitoring configuration for a service, which defines the resolution for the service-level CPUUtilization and MemoryUtilization Amazon CloudWatch metrics.
CfnService.NetworkConfigurationPropertyStructThe network configuration for a task or service.
CfnService.PlacementConstraintPropertyStructAn object representing a constraint on task placement.
CfnService.PlacementStrategyPropertyStructThe task placement strategy for a task or service.
CfnService.SecretPropertyStructAn object representing the secret to expose to your container.
CfnService.ServiceConnectAccessLogConfigurationPropertyStructConfiguration for Service Connect access logging.
CfnService.ServiceConnectClientAliasPropertyStructEach alias ("endpoint") is a fully-qualified name and port number that other tasks ("clients") can use to connect to this service.
CfnService.ServiceConnectConfigurationPropertyStructThe Service Connect configuration of your Amazon ECS service.
CfnService.ServiceConnectServicePropertyStructThe Service Connect service object configuration.
CfnService.ServiceConnectTestTrafficRulesHeaderPropertyStruct
CfnService.ServiceConnectTestTrafficRulesHeaderValuePropertyStruct
CfnService.ServiceConnectTestTrafficRulesPropertyStructThe test traffic routing configuration for Amazon ECS blue/green deployments.
CfnService.ServiceConnectTlsCertificateAuthorityPropertyStructThe certificate root authority that secures your service.
CfnService.ServiceConnectTlsConfigurationPropertyStructThe key that encrypts and decrypts your resources for Service Connect TLS.
CfnService.ServiceManagedEBSVolumeConfigurationPropertyStructThe configuration for the Amazon EBS volume that Amazon ECS creates and manages on your behalf.
CfnService.ServiceRegistryPropertyStructThe details for the service registry.
CfnService.ServiceVolumeConfigurationPropertyStructThe configuration for a volume specified in the task definition as a volume that is configured at launch time.
CfnService.ThresholdConfigurationPropertyStructDefines the failure threshold that the deployment circuit breaker uses to monitor a deployment.
CfnService.TimeoutConfigurationPropertyStructAn object that represents the timeout configurations for Service Connect.
CfnService.VpcLatticeAdvancedConfigurationPropertyStruct
CfnService.VpcLatticeConfigurationPropertyStructThe VPC Lattice configuration for your service that holds the information for the target group(s) Amazon ECS tasks will be registered to.
CfnServicePropsStructProperties for defining a CfnService.
CfnTaskDefinition.AuthorizationConfigPropertyStructThe authorization configuration details for the Amazon EFS file system.
CfnTaskDefinition.ContainerDefinitionPropertyStructThe ContainerDefinition property specifies a container definition.
CfnTaskDefinition.ContainerDependencyPropertyStructThe ContainerDependency property specifies the dependencies defined for container startup and shutdown.
CfnTaskDefinition.DevicePropertyStructThe Device property specifies an object representing a container instance host device.
CfnTaskDefinition.DockerVolumeConfigurationPropertyStructThe DockerVolumeConfiguration property specifies a Docker volume configuration and is used when you use Docker volumes.
CfnTaskDefinition.EFSVolumeConfigurationPropertyStructThis parameter is specified when you're using an Amazon Elastic File System file system for task storage.
CfnTaskDefinition.EnvironmentFilePropertyStructA list of files containing the environment variables to pass to a container.
CfnTaskDefinition.EphemeralStoragePropertyStructThe amount of ephemeral storage to allocate for the task.
CfnTaskDefinition.FirelensConfigurationPropertyStructThe FireLens configuration for the container.
CfnTaskDefinition.FSxAuthorizationConfigPropertyStructThe authorization configuration details for Amazon FSx for Windows File Server file system.
CfnTaskDefinition.FSxWindowsFileServerVolumeConfigurationPropertyStructThis parameter is specified when you're using Amazon FSx for Windows File Server file system for task storage.
CfnTaskDefinition.HealthCheckPropertyStructThe HealthCheck property specifies an object representing a container health check.
CfnTaskDefinition.HostEntryPropertyStructThe HostEntry property specifies a hostname and an IP address that are added to the /etc/hosts file of a container through the extraHosts parameter of its ContainerDefinition resource.
CfnTaskDefinition.HostVolumePropertiesPropertyStructThe HostVolumeProperties property specifies details on a container instance bind mount host volume.
CfnTaskDefinition.InferenceAcceleratorPropertyStruct
CfnTaskDefinition.KernelCapabilitiesPropertyStructThe Linux capabilities to add or remove from the default Docker configuration for a container defined in the task definition.
CfnTaskDefinition.KeyValuePairPropertyStructA key-value pair object.
CfnTaskDefinition.LinuxParametersPropertyStructThe Linux-specific options that are applied to the container, such as Linux KernelCapabilities .
CfnTaskDefinition.LogConfigurationPropertyStructThe LogConfiguration property specifies log configuration options to send to a custom log driver for the container.
CfnTaskDefinition.MountPointPropertyStructThe details for a volume mount point that's used in a container definition.
CfnTaskDefinition.PortMappingPropertyStructThe PortMapping property specifies a port mapping.
CfnTaskDefinition.ProxyConfigurationPropertyStructThe configuration details for the App Mesh proxy.
CfnTaskDefinition.RepositoryCredentialsPropertyStructThe repository credentials for private registry authentication.
CfnTaskDefinition.ResourceRequirementPropertyStructThe type and amount of a resource to assign to a container.
CfnTaskDefinition.RestartPolicyPropertyStructYou can enable a restart policy for each container defined in your task definition, to overcome transient failures faster and maintain task availability.
CfnTaskDefinition.RuntimePlatformPropertyStructInformation about the platform for the Amazon ECS service or task.
CfnTaskDefinition.S3FilesVolumeConfigurationPropertyStructThis parameter is specified when you're using an Amazon S3 Files file system for task storage.
CfnTaskDefinition.SecretPropertyStructAn object representing the secret to expose to your container.
CfnTaskDefinition.SystemControlPropertyStructA list of namespaced kernel parameters to set in the container.
CfnTaskDefinition.TaskDefinitionPlacementConstraintPropertyStructThe constraint on task placement in the task definition.
CfnTaskDefinition.TmpfsPropertyStructThe container path, mount options, and size of the tmpfs mount.
CfnTaskDefinition.UlimitPropertyStructThe ulimit settings to pass to the container.
CfnTaskDefinition.VolumeFromPropertyStructDetails on a data volume from another container in the same task definition.
CfnTaskDefinition.VolumePropertyStructThe data volume configuration for tasks launched using this task definition.
CfnTaskDefinitionPropsStructProperties for defining a CfnTaskDefinition.
CfnTaskSet.AwsVpcConfigurationPropertyStructAn object representing the networking details for a task or service.
CfnTaskSet.CapacityProviderStrategyItemPropertyStructThe details of a capacity provider strategy.
CfnTaskSet.LoadBalancerPropertyStructThe load balancer configuration to use with a service or task set.
CfnTaskSet.NetworkConfigurationPropertyStructThe network configuration for a task or service.
CfnTaskSet.ScalePropertyStructA floating-point percentage of the desired number of tasks to place and keep running in the task set.
CfnTaskSet.ServiceRegistryPropertyStructThe details for the service registry.
CfnTaskSetPropsStructProperties for defining a CfnTaskSet.
CloudMapNamespaceOptionsStructThe options for creating an AWS Cloud Map namespace.
CloudMapNamespaceOptionsBaseStructOptions shared by all ways of setting the default AWS Cloud Map namespace of a cluster.
CloudMapOptionsStructThe options to enabling AWS Cloud Map for an Amazon ECS service.
ClusterAttributesStructThe properties to import from the ECS cluster.
ClusterGrantsFacadeCollection of grant methods for a IClusterRef.
ClusterPropsStructThe properties used to define an ECS cluster.
CommonTaskDefinitionAttributesStructThe common task definition attributes used across all types of task definitions.
CommonTaskDefinitionPropsStructThe common properties for all task definitions.
CompatibilityEnumThe task launch type compatibility requirement.
ContainerDefinitionConstructA container definition is used in a task definition to describe the containers that are launched as part of a task.
ContainerDefinitionOptionsStruct
ContainerDefinitionPropsStructThe properties in a container definition.
ContainerDependencyStructThe details of a dependency on another container in the task definition.
ContainerDependencyConditionEnum
ContainerImageClassConstructs for types of container images.
ContainerImageConfigStructThe configuration for creating a container image.
ContainerInsightsEnumThe CloudWatch Container Insights setting.
ContainerMountPointStructDefines the mount point details for attaching a volume to a container.
CpuArchitectureClassThe CpuArchitecture for Fargate Runtime Platform.
CpuUtilizationScalingPropsStructThe properties for enabling scaling based on CPU utilization.
CredentialSpecClassBase construct for a credential specification (CredSpec).
CredentialSpecConfigStructConfiguration for a credential specification (CredSpec) used for a ECS container.
DeploymentAlarmConfigStructConfiguration for deployment alarms.
DeploymentAlarmOptionsStructOptions for deployment alarms.
DeploymentCircuitBreakerStructThe deployment circuit breaker to use for the service.
DeploymentControllerStructThe deployment controller to use for the service.
DeploymentControllerTypeEnumThe deployment controller type to use for the service.
DeploymentLifecycleHookTargetConfigStructConfiguration for a deployment lifecycle hook target.
DeploymentLifecycleLambdaTargetClassUse an AWS Lambda function as a deployment lifecycle hook target.
DeploymentLifecycleLambdaTargetPropsStructConfiguration for a lambda deployment lifecycle hook.
DeploymentLifecycleStageEnumDeployment lifecycle stages where hooks can be executed.
DeploymentStrategyEnumThe deployment stratergy to use for ECS controller.
DeviceStructA container instance host device.
DevicePermissionEnumPermissions for device access.
DockerVolumeConfigurationStructThe configuration for a Docker volume.
DomainJoinedCredentialSpecClassCredential specification (CredSpec) file.
DomainlessCredentialSpecClassCredential specification for domainless gMSA.
EbsPropagatedTagSourceEnumPropagate tags for EBS Volume Configuration from either service or task definition.
EBSTagSpecificationStructTag Specification for EBS volume.
Ec2ServiceAttributesStructThe properties to import from the service using the EC2 launch type.
Ec2ServicePropsStructThe properties for defining a service using the EC2 launch type.
Ec2TaskDefinitionAttributesStructAttributes used to import an existing EC2 task definition.
Ec2TaskDefinitionPropsStructThe properties for a task definition run on an EC2 cluster.
EcrImageClassAn image from an Amazon ECR repository.
EcsOptimizedImageClassConstruct a Linux or Windows machine image from the latest ECS Optimized AMI published in SSM.
EcsOptimizedImageOptionsStructAdditional configuration properties for EcsOptimizedImage factory functions.
EcsTargetStruct
EfsVolumeConfigurationStructThe configuration for an Elastic FileSystem volume.
EnvironmentFileClassConstructs for types of environment files.
EnvironmentFileConfigStructConfiguration for the environment file.
EnvironmentFileTypeEnumType of environment file to be included in the container definition.
ExecuteCommandConfigurationStructThe details of the execute command configuration.
ExecuteCommandLogConfigurationStructThe log configuration for the results of the execute command actions.
ExecuteCommandLoggingEnumThe log settings to use to for logging the execute command session.
ExistingCloudMapNamespaceOptionsStructThe options for using an existing AWS Cloud Map namespace as the default namespace of a cluster.
ExternalServiceAttributesStructThe properties to import from the service using the External launch type.
ExternalServicePropsStructThe properties for defining a service using the External launch type.
ExternalTaskDefinitionAttributesStructAttributes used to import an existing External task definition.
ExternalTaskDefinitionPropsStructThe properties for a task definition run on an External cluster.
FargatePlatformVersionEnumThe platform version on which to run your service.
FargateServiceAttributesStructThe properties to import from the service using the Fargate launch type.
FargateServicePropsStructThe properties for defining a service using the Fargate launch type.
FargateTaskDefinitionAttributesStructAttributes used to import an existing Fargate task definition.
FargateTaskDefinitionPropsStructThe properties for a task definition.
FileSystemTypeEnumFileSystemType for Service Managed EBS Volume Configuration.
FirelensConfigStructFirelens Configuration https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_firelens.html#firelens-taskdef.
FirelensConfigFileTypeEnumFirelens configuration file type, s3 or file path.
FireLensLogDriverClassFireLens enables you to use task definition parameters to route logs to an AWS service or AWS Partner Network (APN) destination for log storage and analytics.
FireLensLogDriverPropsStructSpecifies the firelens log driver configuration options.
FirelensLogRouterConstructFirelens log router.
FirelensLogRouterDefinitionOptionsStructThe options for creating a firelens log router.
FirelensLogRouterPropsStructThe properties in a firelens log router.
FirelensLogRouterTypeEnumFirelens log router type, fluentbit or fluentd.
FirelensOptionsStructThe options for firelens log router https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_firelens.html#firelens-taskdef-customconfig.
FluentdLogDriverClassA log driver that sends log information to journald Logs.
FluentdLogDriverPropsStructSpecifies the fluentd log driver configuration options.
ForceNewDeploymentStructConfiguration for forcing a new deployment of the service.
GelfCompressionTypeEnumThe type of compression the GELF driver uses to compress each log message.
GelfLogDriverClassA log driver that sends log information to journald Logs.
GelfLogDriverPropsStructSpecifies the journald log driver configuration options.
GenericLogDriverClassA log driver that sends logs to the specified driver.
GenericLogDriverPropsStructThe configuration to use when creating a log driver.
HealthCheckStructThe health check command and associated configuration parameters for the container.
HostStructThe details on a container instance bind mount host volume.
IAlternateTargetInterfaceInterface for configuring alternate target groups for blue/green deployments.
IBaseServiceInterfaceThe interface for BaseService.
IClusterInterfaceA regional grouping of one or more container instances on which you can run tasks and services.
IDeploymentLifecycleHookTargetInterfaceInterface for deployment lifecycle hook targets.
IEc2ServiceInterfaceThe interface for a service using the EC2 launch type on an ECS cluster.
IEc2TaskDefinitionInterfaceThe interface of a task definition run on an EC2 cluster.
IEcsLoadBalancerTargetInterfaceInterface for ECS load balancer target.
IExternalServiceInterfaceThe interface for a service using the External launch type on an ECS cluster.
IExternalTaskDefinitionInterfaceThe interface of a task definition run on an External cluster.
IFargateServiceInterfaceThe interface for a service using the Fargate launch type on an ECS cluster.
IFargateTaskDefinitionInterfaceThe interface of a task definition run on a Fargate cluster.
InferenceAcceleratorStructElastic Inference Accelerator.
InstanceMonitoringEnumThe monitoring configuration for EC2 instances.
IpcModeEnumThe IPC resource namespace to use for the containers in the task.
IServiceInterfaceThe interface for a service.
ITaskDefinitionInterfaceThe interface for all task definitions.
ITaskDefinitionExtensionInterfaceAn extension for Task Definitions.
JournaldLogDriverClassA log driver that sends log information to journald Logs.
JournaldLogDriverPropsStructSpecifies the journald log driver configuration options.
JsonFileLogDriverClassA log driver that sends log information to json-file Logs.
JsonFileLogDriverPropsStructSpecifies the json-file log driver configuration options.
LaunchTypeEnumThe launch type of an ECS service.
LinuxParametersConstructLinux-specific options that are applied to the container.
LinuxParametersPropsStructThe properties for defining Linux-specific options that are applied to the container.
ListenerConfigClassBase class for configuring listener when registering targets.
ListenerRuleConfigurationClassRepresents a listener configuration for advanced load balancer settings.
LoadBalancerTargetOptionsStructProperties for defining an ECS target.
LogDriverClassThe base class for log drivers.
LogDriverConfigStructThe configuration to use when creating a log driver.
LogDriversClassThe base class for log drivers.
MachineImageTypeEnumThe machine image type.
ManagedInstancesCapacityProviderConstructA Managed Instances Capacity Provider.
ManagedInstancesCapacityProviderPropsStructThe options for creating a Managed Instances Capacity Provider.
ManagedStorageConfigurationStructKms Keys for encryption ECS managed storage.
MemoryUtilizationScalingPropsStructThe properties for enabling scaling based on memory utilization.
MountPointStructThe details of data volume mount points for a container.
NetworkModeEnumThe networking mode to use for the containers in the task.
NoneLogDriverClassA log driver that sets the log driver to none (no logs collected).
OperatingSystemFamilyClassThe operating system for Fargate Runtime Platform.
PidModeEnumThe process namespace to use for the containers in the task.
PlacementConstraintClassThe placement constraints to use for tasks in the service. For more information, see Amazon ECS Task Placement Constraints.
PlacementStrategyClassThe placement strategies to use for tasks in the service. For more information, see Amazon ECS Task Placement Strategies.
PortMapClassPortMap ValueObjectClass having by ContainerDefinition.
PortMappingStructPort mappings allow containers to access ports on the host container instance to send or receive traffic.
PropagatedTagSourceEnumPropagate tags from either service or task definition.
PropagateManagedInstancesTagsEnumPropagate tags for Managed Instances.
ProtocolEnumNetwork protocol.
ProxyConfigurationClassThe base class for proxy configurations.
ProxyConfigurationsClassThe base class for proxy configurations.
RepositoryImageClassAn image hosted in a public or private repository.
RepositoryImagePropsStructThe properties for an image hosted in a public or private repository.
RequestCountScalingPropsStructThe properties for enabling scaling based on Application Load Balancer (ALB) request counts.
RuntimePlatformStructThe interface for Runtime Platform.
S3EnvironmentFileClassEnvironment file from S3.
ScalableTaskCountConstructThe scalable attribute representing task count.
ScalableTaskCountPropsStructThe properties of a scalable attribute representing task count.
ScopeEnumThe scope for the Docker volume that determines its lifecycle.
ScratchSpaceStructThe temporary disk space mounted to the container.
SecretClassA secret environment variable.
SecretVersionInfoStructSpecify the secret's version id or version stage.
ServiceConnectClassServiceConnect ValueObjectClass having by ContainerDefinition.
ServiceConnectAccessLogConfigurationStructConfiguration for Service Connect access logs.
ServiceConnectAccessLogFormatEnumThe format of Service Connect access logs.
ServiceConnectPropsStructInterface for Service Connect configuration.
ServiceConnectServiceStructInterface for service connect Service props.
ServiceConnectTlsConfigurationStructTLS configuration for Service Connect service.
ServiceManagedEBSVolumeConfigurationStructRepresents the configuration for an ECS Service managed EBS volume.
ServiceManagedVolumeConstructRepresents a service-managed volume and always configured at launch.
ServiceManagedVolumePropsStructRepresents the Volume configuration for an ECS service.
SplunkLogDriverClassA log driver that sends log information to splunk Logs.
SplunkLogDriverPropsStructSpecifies the splunk log driver configuration options.
SplunkLogFormatEnumLog Message Format.
SyslogLogDriverClassA log driver that sends log information to syslog Logs.
SyslogLogDriverPropsStructSpecifies the syslog log driver configuration options.
SystemControlStructKernel parameters to set in the container.
TagParameterContainerImageClassA special type of ContainerImage that uses an ECR repository for the image, but a CloudFormation Parameter for the tag or digest of the image in that repository.
TagParameterContainerImagePropsStructProperties for TagParameterContainerImage.
TaskDefinitionAttributesStructA reference to an existing task definition.
TaskDefinitionPropsStructThe properties for task definitions.
TaskDefinitionRevisionClassRepresents revision of a task definition, either a specific numbered revision or the latest revision.
TmpfsStructThe details of a tmpfs mount for a container.
TmpfsMountOptionEnumThe supported options for a tmpfs mount for a container.
TrackCustomMetricPropsStructThe properties for enabling target tracking scaling based on a custom CloudWatch metric.
TrafficShiftConfigStructConfiguration for traffic shift during progressive deployments.
UlimitStructThe ulimit settings to pass to the container.
UlimitNameEnumType of resource to set a limit on.
VersionConsistencyEnumState of the container version consistency feature.
VolumeStructA data volume used in a task definition.
VolumeFromStructThe details on a data volume from another container in the same task definition.
WindowsOptimizedVersionEnumECS-optimized Windows version list.