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:
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,
},
});
# 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
)
)
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();
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
}
});
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
Ec2TaskDefinitionandEc2Serviceconstructs to run tasks on Amazon EC2 instances running in your account. - Use the
FargateTaskDefinitionandFargateServiceconstructs to run tasks on instances that are managed for you by AWS. - Use the
ExternalTaskDefinitionandExternalServiceconstructs to run AWS ECS Anywhere tasks on self-managed infrastructure.
Here are the main differences:
- Amazon EC2: instances are under your control. Complete control of task to host allocation. Required to specify at least a memory reservation or limit for every container. Can use Host, Bridge and AwsVpc networking modes. Can attach Classic Load Balancer. Can share volumes between container and host.
- AWS Fargate: tasks run on AWS-managed instances, AWS manages task to host allocation for you. Requires specification of memory and cpu sizes at the taskdefinition level. Only supports AwsVpc networking modes and Application/Network Load Balancers. Only the AWS log driver is supported. Many host features are not supported such as adding kernel capabilities and mounting host devices/volumes inside the container.
- AWS ECS Anywhere: tasks are run and managed by AWS ECS Anywhere on infrastructure owned by the customer. Bridge, Host and None networking modes are supported. Does not support autoscaling, load balancing, cloudmap or attachment of volumes.
For more information on Amazon EC2 vs AWS Fargate, networking and ECS Anywhere see the AWS Documentation: AWS Fargate, Task Networking, ECS Anywhere
Clusters
A Cluster defines the infrastructure to run your tasks on. You can run many tasks on a single cluster.
The following code creates a cluster that can run AWS Fargate tasks:
declare const vpc: ec2.Vpc;
const cluster = new ecs.Cluster(this, 'Cluster', {
vpc,
});
# vpc: ec2.Vpc
cluster = ecs.Cluster(self, "Cluster",
vpc=vpc
)
Vpc vpc;
Cluster cluster = Cluster.Builder.create(this, "Cluster")
.vpc(vpc)
.build();
Vpc vpc;
var cluster = new Cluster(this, "Cluster", new ClusterProps {
Vpc = vpc
});
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:
declare const key: kms.Key;
const cluster = new ecs.Cluster(this, 'Cluster', {
managedStorageConfiguration: {
fargateEphemeralStorageKmsKey: key,
kmsKey: key,
},
});
# key: kms.Key
cluster = ecs.Cluster(self, "Cluster",
managed_storage_configuration=ecs.ManagedStorageConfiguration(
fargate_ephemeral_storage_kms_key=key,
kms_key=key
)
)
Key key;
Cluster cluster = Cluster.Builder.create(this, "Cluster")
.managedStorageConfiguration(ManagedStorageConfiguration.builder()
.fargateEphemeralStorageKmsKey(key)
.kmsKey(key)
.build())
.build();
Key key;
var cluster = new Cluster(this, "Cluster", new ClusterProps {
ManagedStorageConfiguration = new ManagedStorageConfiguration {
FargateEphemeralStorageKmsKey = key,
KmsKey = key
}
});
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.
const clusterArn = 'arn:aws:ecs:us-east-1:012345678910:cluster/clusterName';
const cluster = ecs.Cluster.fromClusterArn(this, 'Cluster', clusterArn);
cluster_arn = "arn:aws:ecs:us-east-1:012345678910:cluster/clusterName"
cluster = ecs.Cluster.from_cluster_arn(self, "Cluster", cluster_arn)
String clusterArn = "arn:aws:ecs:us-east-1:012345678910:cluster/clusterName";
ICluster cluster = Cluster.fromClusterArn(this, "Cluster", clusterArn);
var clusterArn = "arn:aws:ecs:us-east-1:012345678910:cluster/clusterName";
var cluster = Cluster.FromClusterArn(this, "Cluster", clusterArn);
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:
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);
# 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)
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);
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);
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:
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'),
});
# 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")
)
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();
Vpc vpc;
var autoScalingGroup = new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
MachineImage = EcsOptimizedImage.AmazonLinux(new EcsOptimizedImageOptions { CachedInContext = true }),
Vpc = vpc,
InstanceType = new InstanceType("t2.micro")
});
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.
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'),
});
# 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")
)
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();
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")
});
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:
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);
# 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)
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);
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);
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.
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],
})
)
# 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]
))
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());
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 }
}));
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.
// 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);
# 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)
// 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);
// 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);
// 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:
declare const cluster: ecs.Cluster;
cluster.addCapacity('bottlerocket-asg', {
minCapacity: 2,
instanceType: new ec2.InstanceType('c5.large'),
machineImage: new ecs.BottleRocketImage(),
});
# cluster: ecs.Cluster
cluster.add_capacity("bottlerocket-asg",
min_capacity=2,
instance_type=ec2.InstanceType("c5.large"),
machine_image=ecs.BottleRocketImage()
)
Cluster cluster;
cluster.addCapacity("bottlerocket-asg", AddCapacityOptions.builder()
.minCapacity(2)
.instanceType(new InstanceType("c5.large"))
.machineImage(new BottleRocketImage())
.build());
Cluster cluster;
cluster.AddCapacity("bottlerocket-asg", new AddCapacityOptions {
MinCapacity = 2,
InstanceType = new InstanceType("c5.large"),
MachineImage = new BottleRocketImage()
});
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:
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,
}),
});
# 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
)
)
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());
Cluster cluster;
cluster.AddCapacity("bottlerocket-asg", new AddCapacityOptions {
InstanceType = new InstanceType("p3.2xlarge"),
MachineImage = new BottleRocketImage(new BottleRocketImageProps {
Variant = BottlerocketEcsVariant.AWS_ECS_2_NVIDIA
})
});
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.
declare const cluster: ecs.Cluster;
cluster.addCapacity('graviton-cluster', {
minCapacity: 2,
instanceType: new ec2.InstanceType('c6g.large'),
machineImage: ecs.EcsOptimizedImage.amazonLinux2(ecs.AmiHardwareType.ARM),
});
# 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)
)
Cluster cluster;
cluster.addCapacity("graviton-cluster", AddCapacityOptions.builder()
.minCapacity(2)
.instanceType(new InstanceType("c6g.large"))
.machineImage(EcsOptimizedImage.amazonLinux2(AmiHardwareType.ARM))
.build());
Cluster cluster;
cluster.AddCapacity("graviton-cluster", new AddCapacityOptions {
MinCapacity = 2,
InstanceType = new InstanceType("c6g.large"),
MachineImage = EcsOptimizedImage.AmazonLinux2(AmiHardwareType.ARM)
});
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:
declare const cluster: ecs.Cluster;
cluster.addCapacity('graviton-cluster', {
minCapacity: 2,
instanceType: new ec2.InstanceType('c6g.large'),
machineImageType: ecs.MachineImageType.BOTTLEROCKET,
});
# cluster: ecs.Cluster
cluster.add_capacity("graviton-cluster",
min_capacity=2,
instance_type=ec2.InstanceType("c6g.large"),
machine_image_type=ecs.MachineImageType.BOTTLEROCKET
)
Cluster cluster;
cluster.addCapacity("graviton-cluster", AddCapacityOptions.builder()
.minCapacity(2)
.instanceType(new InstanceType("c6g.large"))
.machineImageType(MachineImageType.BOTTLEROCKET)
.build());
Cluster cluster;
cluster.AddCapacity("graviton-cluster", new AddCapacityOptions {
MinCapacity = 2,
InstanceType = new InstanceType("c6g.large"),
MachineImageType = MachineImageType.BOTTLEROCKET
});
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.
declare const cluster: ecs.Cluster;
cluster.addCapacity('neuron-cluster', {
minCapacity: 2,
instanceType: new ec2.InstanceType('inf1.xlarge'),
machineImage: ecs.EcsOptimizedImage.amazonLinux2(ecs.AmiHardwareType.NEURON),
});
# 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)
)
Cluster cluster;
cluster.addCapacity("neuron-cluster", AddCapacityOptions.builder()
.minCapacity(2)
.instanceType(new InstanceType("inf1.xlarge"))
.machineImage(EcsOptimizedImage.amazonLinux2(AmiHardwareType.NEURON))
.build());
Cluster cluster;
cluster.AddCapacity("neuron-cluster", new AddCapacityOptions {
MinCapacity = 2,
InstanceType = new InstanceType("inf1.xlarge"),
MachineImage = EcsOptimizedImage.AmazonLinux2(AmiHardwareType.NEURON)
});
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.
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,
});
# 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
)
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());
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
});
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.
// 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,
});
# 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
)
// 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());
// 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
});
// 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.
const cluster = new ecs.Cluster(this, 'Cluster', {
containerInsightsV2: ecs.ContainerInsights.ENHANCED
});
cluster = ecs.Cluster(self, "Cluster",
container_insights_v2=ecs.ContainerInsights.ENHANCED
)
Cluster cluster = Cluster.Builder.create(this, "Cluster")
.containerInsightsV2(ContainerInsights.ENHANCED)
.build();
var cluster = new Cluster(this, "Cluster", new ClusterProps {
ContainerInsightsV2 = ContainerInsights.ENHANCED
});
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):
const fargateTaskDefinition = new ecs.FargateTaskDefinition(this, 'TaskDef', {
memoryLimitMiB: 512,
cpu: 256,
});
fargate_task_definition = ecs.FargateTaskDefinition(self, "TaskDef",
memory_limit_mi_b=512,
cpu=256
)
FargateTaskDefinition fargateTaskDefinition = FargateTaskDefinition.Builder.create(this, "TaskDef")
.memoryLimitMiB(512)
.cpu(256)
.build();
var fargateTaskDefinition = new FargateTaskDefinition(this, "TaskDef", new FargateTaskDefinitionProps {
MemoryLimitMiB = 512,
Cpu = 256
});
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:
const fargateTaskDefinition = new ecs.FargateTaskDefinition(this, 'TaskDef', {
memoryLimitMiB: 512,
cpu: 256,
ephemeralStorageGiB: 100,
});
fargate_task_definition = ecs.FargateTaskDefinition(self, "TaskDef",
memory_limit_mi_b=512,
cpu=256,
ephemeral_storage_gi_b=100
)
FargateTaskDefinition fargateTaskDefinition = FargateTaskDefinition.Builder.create(this, "TaskDef")
.memoryLimitMiB(512)
.cpu(256)
.ephemeralStorageGiB(100)
.build();
var fargateTaskDefinition = new FargateTaskDefinition(this, "TaskDef", new FargateTaskDefinitionProps {
MemoryLimitMiB = 512,
Cpu = 256,
EphemeralStorageGiB = 100
});
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:
const fargateTaskDefinition = new ecs.FargateTaskDefinition(this, 'TaskDef', {
runtimePlatform: {
operatingSystemFamily: ecs.OperatingSystemFamily.LINUX,
cpuArchitecture: ecs.CpuArchitecture.ARM64,
},
memoryLimitMiB: 512,
cpu: 256,
pidMode: ecs.PidMode.TASK,
});
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
)
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();
var fargateTaskDefinition = new FargateTaskDefinition(this, "TaskDef", new FargateTaskDefinitionProps {
RuntimePlatform = new RuntimePlatform {
OperatingSystemFamily = OperatingSystemFamily.LINUX,
CpuArchitecture = CpuArchitecture.ARM64
},
MemoryLimitMiB = 512,
Cpu = 256,
PidMode = PidMode.TASK
});
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():
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 ...
});
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")
)
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());
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")
});
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:
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 ...
});
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
)
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());
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
});
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:
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 ...
});
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
)
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());
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
});
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:
declare const taskDefinition: ecs.TaskDefinition;
taskDefinition.addContainer("WebContainer", {
image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
memoryLimitMiB: 1024,
portMappings: [{ containerPort: 3000 }],
});
# 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)]
)
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());
TaskDefinition taskDefinition;
taskDefinition.AddContainer("WebContainer", new ContainerDefinitionOptions {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
MemoryLimitMiB = 1024,
PortMappings = new [] { new PortMapping { ContainerPort = 3000 } }
});
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():
declare const container: ecs.ContainerDefinition;
container.addPortMappings({
containerPort: 3000,
});
# container: ecs.ContainerDefinition
container.add_port_mappings(
container_port=3000
)
ContainerDefinition container;
container.addPortMappings(PortMapping.builder()
.containerPort(3000)
.build());
ContainerDefinition container;
container.AddPortMappings(new PortMapping {
ContainerPort = 3000
});
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.
declare const container: ecs.ContainerDefinition;
container.addPortMappings({
containerPort: ecs.ContainerDefinition.CONTAINER_PORT_USE_RANGE,
containerPortRange: '8080-8081',
});
# container: ecs.ContainerDefinition
container.add_port_mappings(
container_port=ecs.ContainerDefinition.CONTAINER_PORT_USE_RANGE,
container_port_range="8080-8081"
)
ContainerDefinition container;
container.addPortMappings(PortMapping.builder()
.containerPort(ContainerDefinition.CONTAINER_PORT_USE_RANGE)
.containerPortRange("8080-8081")
.build());
ContainerDefinition container;
container.AddPortMappings(new PortMapping {
ContainerPort = ContainerDefinition.CONTAINER_PORT_USE_RANGE,
ContainerPortRange = "8080-8081"
});
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():
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);
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)
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);
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);
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:
const taskDefinition = new ecs.TaskDefinition(this, 'TaskDef', {
memoryMiB: '512',
cpu: '256',
networkMode: ecs.NetworkMode.AWS_VPC,
compatibility: ecs.Compatibility.EC2_AND_FARGATE,
});
task_definition = ecs.TaskDefinition(self, "TaskDef",
memory_mi_b="512",
cpu="256",
network_mode=ecs.NetworkMode.AWS_VPC,
compatibility=ecs.Compatibility.EC2_AND_FARGATE
)
TaskDefinition taskDefinition = TaskDefinition.Builder.create(this, "TaskDef")
.memoryMiB("512")
.cpu("256")
.networkMode(NetworkMode.AWS_VPC)
.compatibility(Compatibility.EC2_AND_FARGATE)
.build();
var taskDefinition = new TaskDefinition(this, "TaskDef", new TaskDefinitionProps {
MemoryMiB = "512",
Cpu = "256",
NetworkMode = NetworkMode.AWS_VPC,
Compatibility = Compatibility.EC2_AND_FARGATE
});
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:
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);
# 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)
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);
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);
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.
declare const taskDefinition: ecs.TaskDefinition;
taskDefinition.addContainer("Container", {
image: ecs.ContainerImage.fromRegistry("amazon/amazon-ecs-sample"),
interactive: true,
});
# task_definition: ecs.TaskDefinition
task_definition.add_container("Container",
image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample"),
interactive=True
)
TaskDefinition taskDefinition;
taskDefinition.addContainer("Container", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("amazon/amazon-ecs-sample"))
.interactive(true)
.build());
TaskDefinition taskDefinition;
taskDefinition.AddContainer("Container", new ContainerDefinitionOptions {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
Interactive = true
});
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 aDockerfilein your source directory.ecs.ContainerImage.fromDockerImageAsset(asset): uses an existingaws-cdk-lib/aws-ecr-assets.DockerImageAssetas a container image.ecs.ContainerImage.fromTarball(file): use an existing tarball.new ecs.TagParameterContainerImage(repository): use the given ECR repository as the image but a CloudFormation parameter as the tag.
Environment variables
To pass environment variables to the container, you can use the environment, environmentFiles, and secrets props.
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'));
# 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"))
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"));
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"));
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:
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,
}),
});
# 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
)
)
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());
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
})
});
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:
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',
},
],
});
# 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"
)
]
)
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());
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"
} }
});
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.
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),
});
# 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)
)
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());
TaskDefinition taskDefinition;
taskDefinition.AddContainer("container", new ContainerDefinitionOptions {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
EnableRestartPolicy = true,
RestartIgnoredExitCodes = new [] { 0, 127 },
RestartAttemptPeriod = Duration.Seconds(360)
});
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.
new ecs.Ec2TaskDefinition(this, 'Ec2TaskDefinition', {
enableFaultInjection: true,
});
ecs.Ec2TaskDefinition(self, "Ec2TaskDefinition",
enable_fault_injection=True
)
Ec2TaskDefinition.Builder.create(this, "Ec2TaskDefinition")
.enableFaultInjection(true)
.build();
new Ec2TaskDefinition(this, "Ec2TaskDefinition", new Ec2TaskDefinitionProps {
EnableFaultInjection = true
});
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:
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');
# 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")
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");
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");
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
// 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'),
});
# 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")
)
// 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());
// 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")
});
// 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:
// 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)],
});
# 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)]
)
// 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());
// 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) }
});
// 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:
// 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')],
});
# 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")]
)
// 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());
// 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") }
});
// 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
// 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'),
});
# 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")
)
// 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());
// 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")
});
// 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.
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,
},
});
# 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
)
)
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();
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
}
});
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:
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;
const service = new ecs.ExternalService(this, 'Service', {
cluster,
taskDefinition,
desiredCount: 5,
minHealthyPercent: 100,
});
# 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
)
Cluster cluster;
TaskDefinition taskDefinition;
ExternalService service = ExternalService.Builder.create(this, "Service")
.cluster(cluster)
.taskDefinition(taskDefinition)
.desiredCount(5)
.minHealthyPercent(100)
.build();
Cluster cluster;
TaskDefinition taskDefinition;
var service = new ExternalService(this, "Service", new ExternalServiceProps {
Cluster = cluster,
TaskDefinition = taskDefinition,
DesiredCount = 5,
MinHealthyPercent = 100
});
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:
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,
});
# 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
)
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();
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
});
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.
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
},
});
# 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
)
)
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();
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
}
});
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.
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,
});
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
)
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());
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
});
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
deploymentControlleris set toDeploymentControllerType.ECS, which is the default.
Troubleshooting circular dependencies
I saw this info message during synth time. What do I do?
Deployment alarm ({"Ref":"MyAlarmABC1234"}) enabled on MyEcsService may cause a
circular dependency error when this stack deploys. The alarm name references the
alarm's logical id, or another resource. See the 'Deployment alarms' section in
the module README for more details.
If your app deploys successfully with this message, you can disregard it. But it indicates that you could encounter a circular dependency error when you try to deploy. If you want to alarm on metrics produced by the service, there will be a circular dependency between the service and its deployment alarms. In this case, there are two options to avoid the circular dependency.
- Define the physical name for the alarm. Use a defined physical name that is unique within the deployment environment for the alarm name when creating the alarm, and re-use the defined name. This name could be a hardcoded string, a string generated based on the environment, or could reference another resource that does not depend on the service.
- Define the physical name for the service. Then, don't use
metricCpuUtilization()or similar methods. Create the metric object separately by referencing the service metrics using this name.
Option 1, defining a physical name for the alarm:
import * 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,
});
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
)
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());
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
});
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:
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,
});
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
)
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());
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
});
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:
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
})],
});
# 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
)]
)
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());
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
}) }
});
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.
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
}),
},
);
# 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
)
)
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());
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
})
});
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:
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);
# 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)
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);
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);
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:
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,
}));
# 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
))
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()));
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
}));
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:
LoadBalancedFargateServiceLoadBalancedEc2Service
Import existing services
Ec2Service and FargateService provide methods to import existing EC2/Fargate services. The ARN of the existing service has to be specified to import the service.
Since AWS has changed the ARN format for ECS, feature flag @aws-cdk/aws-ecs:arnFormatIncludesClusterName must be enabled to use the new ARN format. The feature flag changes behavior for the entire CDK project. Therefore it is not possible to mix the old and the new format in one CDK project.
declare const cluster: ecs.Cluster;
// Import service from EC2 service attributes
const 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');
# 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")
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");
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");
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.
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 },
});
# 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)
)
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();
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 }
});
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:
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;
const service = new ecs.FargateService(this, 'Service', {
cluster,
taskDefinition,
availabilityZoneRebalancing: ecs.AvailabilityZoneRebalancing.ENABLED,
});
# cluster: ecs.Cluster
# task_definition: ecs.TaskDefinition
service = ecs.FargateService(self, "Service",
cluster=cluster,
task_definition=task_definition,
availability_zone_rebalancing=ecs.AvailabilityZoneRebalancing.ENABLED
)
Cluster cluster;
TaskDefinition taskDefinition;
FargateService service = FargateService.Builder.create(this, "Service")
.cluster(cluster)
.taskDefinition(taskDefinition)
.availabilityZoneRebalancing(AvailabilityZoneRebalancing.ENABLED)
.build();
Cluster cluster;
TaskDefinition taskDefinition;
var service = new FargateService(this, "Service", new FargateServiceProps {
Cluster = cluster,
TaskDefinition = taskDefinition,
AvailabilityZoneRebalancing = AvailabilityZoneRebalancing.ENABLED
});
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-zoneas a task placement constraint.
Task Auto-Scaling
You can configure the task count of a service to match demand. Task auto-scaling is configured by calling autoScaleTaskCount():
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,
});
# 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
)
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());
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
});
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:
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'
}],
}],
}));
# 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"
)]
)]
))
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());
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"
} }
} }
}));
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
// 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),
}),
});
# 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)
)
)
// 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());
// 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)
})
});
// 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
// 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(),
});
# 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()
)
// 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());
// 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()
});
// 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
// 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' }),
});
# 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")
)
// 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());
// 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" })
});
// 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
// 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(),
});
# 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()
)
// 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());
// 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()
});
// 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
// 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(),
});
# 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()
)
// 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());
// 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()
});
// 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
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',
}),
});
# 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"
)
)
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());
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"
})
});
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
// 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(),
});
# 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()
)
// 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());
// 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()
});
// 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
// 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',
},
}),
});
# 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"
}
)
)
// 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());
// 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" }
}
})
});
// 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.
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),
},
}),
});
# 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)}
)
)
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());
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) } }
})
});
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.
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',
},
}),
});
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"
}
)
)
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());
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" }
}
})
});
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.
// 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',
},
}),
});
# 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"
}
)
)
// 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());
// 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" }
}
})
});
// 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).
// 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(),
});
# 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()
)
// 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());
// 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()
});
// 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:
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,
},
});
# 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
)
)
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();
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
}
});
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:
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,
},
});
# 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
)
)
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();
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
}
});
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:
declare const cloudMapService: cloudmap.Service;
declare const ecsService: ecs.FargateService;
ecsService.associateCloudMapService({
service: cloudMapService,
});
# cloud_map_service: cloudmap.Service
# ecs_service: ecs.FargateService
ecs_service.associate_cloud_map_service(
service=cloud_map_service
)
Service cloudMapService;
FargateService ecsService;
ecsService.associateCloudMapService(AssociateCloudMapServiceOptions.builder()
.service(cloudMapService)
.build());
Service cloudMapService;
FargateService ecsService;
ecsService.AssociateCloudMapService(new AssociateCloudMapServiceOptions {
Service = cloudMapService
});
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:
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,
});
# 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
)
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());
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
});
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:
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,
});
# 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
)
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());
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
});
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.
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,
},
],
});
# 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
)
]
)
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();
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
} }
});
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
enableManagedTerminationProtectiontofalseon the Auto Scaling Group Capacity Provider. If you'd rather not disable Managed Termination Protection, you can manually delete the Auto Scaling Group. For other workarounds, see this GitHub issue.
Managed instance draining facilitates graceful termination of Amazon ECS instances. This allows your service workloads to stop safely and be rescheduled to non-terminating instances. Infrastructure maintenance and updates are 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.
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,
},
],
});
# 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
)
]
)
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();
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
} }
});
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
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,
},
],
});
# 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
)
]
)
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();
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
} }
});
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.
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,
},
],
});
# 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
)
]
)
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();
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
} }
});
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:
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,
},
});
# 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
)
)
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();
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
}
});
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:
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
# 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"
Cluster cluster;
TaskDefinition taskDefinition;
ManagedInstancesCapacityProvider miCapacityProvider;
FargateService service = FargateService.Builder.create(this, "Service")
.cluster(cluster)
.taskDefinition(taskDefinition)
.capacityProviderStrategies(List.of(CapacityProviderStrategy.builder()
.capacityProvider(miCapacityProvider.getCapacityProviderName())
.weight(1)
.build()))
.build();
// Escape hatch: Force launchType at the CloudFormation level to prevent service replacement
CfnService cfnService = (CfnService)service.getNode().getDefaultChild();
cfnService.getLaunchType() = "FARGATE";
Cluster 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";
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.
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 },
]);
# 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
])
AsgCapacityProvider capacityProvider;
Cluster cluster = Cluster.Builder.create(this, "EcsCluster")
.enableFargateCapacityProviders(true)
.build();
cluster.addAsgCapacityProvider(capacityProvider);
cluster.addDefaultCapacityProviderStrategy(List.of(CapacityProviderStrategy.builder().capacityProvider("FARGATE").base(10).weight(50).build(), CapacityProviderStrategy.builder().capacityProvider("FARGATE_SPOT").weight(50).build()));
AsgCapacityProvider capacityProvider;
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 } });
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),
},
})
declare const capacityProvider: ecs.AsgCapacityProvider;
const cluster = new ecs.Cluster(this, 'EcsCluster', {
enableFargateCapacityProviders: true,
});
cluster.addAsgCapacityProvider(capacityProvider);
cluster.addDefaultCapacityProviderStrategy([
{ capacityProvider: capacityProvider.capacityProviderName },
]);
# 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
])
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()));
AsgCapacityProvider capacityProvider;
var cluster = new Cluster(this, "EcsCluster", new ClusterProps {
EnableFargateCapacityProviders = true
});
cluster.AddAsgCapacityProvider(capacityProvider);
cluster.AddDefaultCapacityProviderStrategy(new [] { new CapacityProviderStrategy { CapacityProvider = capacityProvider.CapacityProviderName } });
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.
const inferenceAccelerators = [{
deviceName: 'device1',
deviceType: 'eia2.medium',
}];
const taskDefinition = new ecs.Ec2TaskDefinition(this, 'Ec2TaskDef', {
inferenceAccelerators,
});
inference_accelerators = [{
"device_name": "device1",
"device_type": "eia2.medium"
}]
task_definition = ecs.Ec2TaskDefinition(self, "Ec2TaskDef",
inference_accelerators=inference_accelerators
)
Map<String, String>[] inferenceAccelerators = List.of(Map.of(
"deviceName", "device1",
"deviceType", "eia2.medium"));
Ec2TaskDefinition taskDefinition = Ec2TaskDefinition.Builder.create(this, "Ec2TaskDef")
.inferenceAccelerators(inferenceAccelerators)
.build();
IDictionary<string, string>[] inferenceAccelerators = new [] { new Dictionary<string, string> {
{ "deviceName", "device1" },
{ "deviceType", "eia2.medium" }
} };
var taskDefinition = new Ec2TaskDefinition(this, "Ec2TaskDef", new Ec2TaskDefinitionProps {
InferenceAccelerators = inferenceAccelerators
});
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.
declare const taskDefinition: ecs.TaskDefinition;
const inferenceAcceleratorResources = ['device1'];
taskDefinition.addContainer('cont', {
image: ecs.ContainerImage.fromRegistry('test'),
memoryLimitMiB: 1024,
inferenceAcceleratorResources,
});
# 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
)
TaskDefinition taskDefinition;
String[] inferenceAcceleratorResources = List.of("device1");
taskDefinition.addContainer("cont", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("test"))
.memoryLimitMiB(1024)
.inferenceAcceleratorResources(inferenceAcceleratorResources)
.build());
TaskDefinition taskDefinition;
var inferenceAcceleratorResources = new [] { "device1" };
taskDefinition.AddContainer("cont", new ContainerDefinitionOptions {
Image = ContainerImage.FromRegistry("test"),
MemoryLimitMiB = 1024,
InferenceAcceleratorResources = inferenceAcceleratorResources
});
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.
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;
const service = new ecs.Ec2Service(this, 'Service', {
cluster,
taskDefinition,
minHealthyPercent: 100,
enableExecuteCommand: true,
});
# 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
)
Cluster cluster;
TaskDefinition taskDefinition;
Ec2Service service = Ec2Service.Builder.create(this, "Service")
.cluster(cluster)
.taskDefinition(taskDefinition)
.minHealthyPercent(100)
.enableExecuteCommand(true)
.build();
Cluster cluster;
TaskDefinition taskDefinition;
var service = new Ec2Service(this, "Service", new Ec2ServiceProps {
Cluster = cluster,
TaskDefinition = taskDefinition,
MinHealthyPercent = 100,
EnableExecuteCommand = true
});
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.
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,
},
});
# 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
)
)
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();
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
}
});
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.
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,
},
],
},
});
# 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
)
]
)
)
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();
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
} }
}
});
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.
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;
const service = new ecs.FargateService(this, 'Service', {
cluster,
taskDefinition,
minHealthyPercent: 100,
});
service.enableServiceConnect();
# 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()
Cluster cluster;
TaskDefinition taskDefinition;
FargateService service = FargateService.Builder.create(this, "Service")
.cluster(cluster)
.taskDefinition(taskDefinition)
.minHealthyPercent(100)
.build();
service.enableServiceConnect();
Cluster cluster;
TaskDefinition taskDefinition;
var service = new FargateService(this, "Service", new FargateServiceProps {
Cluster = cluster,
TaskDefinition = taskDefinition,
MinHealthyPercent = 100
});
service.EnableServiceConnect();
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.
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',
},
],
},
});
# 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"
)
]
)
)
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();
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"
} }
}
});
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.
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),
},
],
},
});
# 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)
)
]
)
)
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();
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)
} }
}
});
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.
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',
}),
},
});
# 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"
)
)
)
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();
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"
})
}
});
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 formatServiceConnectAccessLogFormat.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().
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);
# 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)
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);
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);
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.
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);
# 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)
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);
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);
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.
const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');
taskDefinition.addContainer('TheContainer', {
image: ecs.ContainerImage.fromRegistry('example-image'),
pseudoTerminal: true
});
task_definition = ecs.Ec2TaskDefinition(self, "TaskDef")
task_definition.add_container("TheContainer",
image=ecs.ContainerImage.from_registry("example-image"),
pseudo_terminal=True
)
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("example-image"))
.pseudoTerminal(true)
.build());
var taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.AddContainer("TheContainer", new ContainerDefinitionOptions {
Image = ContainerImage.FromRegistry("example-image"),
PseudoTerminal = true
});
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.
const taskDefinition = new ecs.Ec2TaskDefinition(this, 'TaskDef');
taskDefinition.addContainer('TheContainer', {
image: ecs.ContainerImage.fromRegistry('example-image'),
versionConsistency: ecs.VersionConsistency.DISABLED,
});
task_definition = ecs.Ec2TaskDefinition(self, "TaskDef")
task_definition.add_container("TheContainer",
image=ecs.ContainerImage.from_registry("example-image"),
version_consistency=ecs.VersionConsistency.DISABLED
)
Ec2TaskDefinition taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.addContainer("TheContainer", ContainerDefinitionOptions.builder()
.image(ContainerImage.fromRegistry("example-image"))
.versionConsistency(VersionConsistency.DISABLED)
.build());
var taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.AddContainer("TheContainer", new ContainerDefinitionOptions {
Image = ContainerImage.FromRegistry("example-image"),
VersionConsistency = VersionConsistency.DISABLED
});
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.
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,
}],
});
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
)]
)
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());
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
} }
});
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.
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',
},
});
# 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"
)
)
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();
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"
}
});
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.
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);
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)
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);
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);
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:
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);
# 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)
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);
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);
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.0stepBakeTime: 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:
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);
# 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)
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);
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);
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.0stepBakeTime: 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
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,
});
# 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
)
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();
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
});
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).
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');
# 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")
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");
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");
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.
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(),
},
});
# 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()
)
)
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();
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()
}
});
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:
new ecs.CfnCluster(this, 'Cluster')
.with(new ecs.mixins.ClusterSettings([{ name: 'containerInsights', value: 'enhanced' }]));
ecs.CfnCluster(self, "Cluster").with(ecs.mixins.ClusterSettings([name="containerInsights", value="enhanced"]))
new CfnCluster(this, "Cluster").with(new ClusterSettings(List.of(ClusterSettingsProperty.builder().name("containerInsights").value("enhanced").build())));
new CfnCluster(this, "Cluster").With(new Mixins.ClusterSettings(new [] { new ClusterSettingsProperty { Name = "containerInsights", Value = "enhanced" } }));
ecs.NewCfnCluster(this, jsii.String("Cluster")).With(mixins.NewClusterSettings([]ClusterSettingsProperty{
&ClusterSettingsProperty{
Name: jsii.String("containerInsights"),
Value: jsii.String("enhanced"),
},
}))
Types
| Name | Kind | Summary |
|---|---|---|
BaseService | Construct (L2) | The base class for Ec2Service and FargateService services. |
Cluster | Construct (L2) | A regional grouping of one or more container instances on which you can run tasks and services. |
Ec2Service | Construct (L2) | This creates a service using the EC2 launch type on an ECS cluster. |
Ec2TaskDefinition | Construct (L2) | The details of a task definition run on an EC2 cluster. |
ExternalService | Construct (L2) | This creates a service using the External launch type on an ECS cluster. |
ExternalTaskDefinition | Construct (L2) | The details of a task definition run on an External cluster. |
FargateService | Construct (L2) | This creates a service using the Fargate launch type on an ECS cluster. |
FargateTaskDefinition | Construct (L2) | The details of a task definition run on a Fargate cluster. |
TaskDefinition | Construct (L2) | The base class for all task definitions. |
CfnCapacityProvider | Construct (L1) | Creates a capacity provider. |
CfnCluster | Construct (L1) | The AWS::ECS::Cluster resource creates an Amazon Elastic Container Service (Amazon ECS) cluster. |
CfnClusterCapacityProviderAssociations | Construct (L1) | The AWS::ECS::ClusterCapacityProviderAssociations resource associates one or more capacity providers and a default capacity provider strategy with a cluster. |
CfnDaemon | Construct (L1) | Information about a daemon resource. |
CfnDaemonTaskDefinition | Construct (L1) | The details of a daemon task definition. |
CfnExpressGatewayService | Construct (L1) | Creates an Express service that simplifies deploying containerized web applications on Amazon ECS with managed AWS infrastructure. |
CfnPrimaryTaskSet | Construct (L1) | Modifies which task set in a service is the primary task set. |
CfnService | Construct (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. |
CfnTaskDefinition | Construct (L1) | Registers a new task definition from the supplied family and containerDefinitions . |
CfnTaskSet | Construct (L1) | Create a task set in the specified cluster and service. |
AddAutoScalingGroupCapacityOptions | Struct | The properties for adding an AutoScalingGroup. |
AddCapacityOptions | Struct | The properties for adding instance capacity to an AutoScalingGroup. |
AlarmBehavior | Enum | Deployment behavior when an ECS Service Deployment Alarm is triggered. |
AlternateTarget | Class | Configuration for alternate target groups used in blue/green deployments with load balancers. |
AlternateTargetConfig | Struct | Configuration returned by AlternateTargetConfiguration.bind(). |
AlternateTargetOptions | Struct | Options for AlternateTarget configuration. |
AlternateTargetProps | Struct | Properties for AlternateTarget configuration. |
AmiHardwareType | Enum | The ECS-optimized AMI variant to use. |
AppMeshProxyConfiguration | Class | The class for App Mesh proxy configurations. |
AppMeshProxyConfigurationConfigProps | Struct | The configuration to use when setting an App Mesh proxy configuration. |
AppMeshProxyConfigurationProps | Struct | Interface for setting the properties of proxy configuration. |
AppProtocol | Class | Service connect app protocol. |
AsgCapacityProvider | Construct | An Auto Scaling Group Capacity Provider. |
AsgCapacityProviderProps | Struct | The options for creating an Auto Scaling Group Capacity Provider. |
AssetEnvironmentFile | Class | Environment file from a local directory. |
AssetImage | Class | An image that will be built from a local directory with a Dockerfile. |
AssetImageProps | Struct | The properties for building an AssetImage. |
AssociateCloudMapServiceOptions | Struct | The options for using a cloudmap service. |
AuthorizationConfig | Struct | The authorization configuration details for the Amazon EFS file system. |
AvailabilityZoneRebalancing | Enum | Indicates whether to use Availability Zone rebalancing for an ECS service. |
AwsLogDriver | Class | A log driver that sends log information to CloudWatch Logs. |
AwsLogDriverMode | Enum | awslogs provides two modes for delivering messages from the container to the log driver. |
AwsLogDriverProps | Struct | Specifies the awslogs log driver configuration options. |
BaseLogDriverProps | Struct | |
BaseMountPoint | Struct | The base details of where a volume will be mounted within a container. |
BaseServiceOptions | Struct | The properties for the base Ec2Service or FargateService service. |
BaseServiceProps | Struct | Complete base service properties that are required to be supplied by the implementation of the BaseService class. |
BinPackResource | Enum | Instance resource used for bin packing. |
BottlerocketEcsVariant | Enum | Amazon ECS variant. |
BottleRocketImage | Class | Construct an Bottlerocket image from the latest AMI published in SSM. |
BottleRocketImageProps | Struct | Properties for BottleRocketImage. |
BuiltInAttributes | Class | The built-in container instance attributes. |
Capability | Enum | A Linux capability. |
CapacityOptionType | Enum | The capacity option type for instances launched by a Managed Instances Capacity Provider. |
CapacityProviderStrategy | Struct | A Capacity Provider strategy to use for the service. |
CfnCapacityProvider.AcceleratorCountRequestProperty | Struct | The minimum and maximum number of accelerators (such as GPUs) for instance type selection. |
CfnCapacityProvider.AcceleratorTotalMemoryMiBRequestProperty | Struct | The minimum and maximum total accelerator memory in mebibytes (MiB) for instance type selection. |
CfnCapacityProvider.AutoRepairConfigurationProperty | Struct | |
CfnCapacityProvider.AutoScalingGroupProviderProperty | Struct | The details of the Auto Scaling group for the capacity provider. |
CfnCapacityProvider.BaselineEbsBandwidthMbpsRequestProperty | Struct | The minimum and maximum baseline Amazon EBS bandwidth in megabits per second (Mbps) for instance type selection. |
CfnCapacityProvider.CapacityReservationRequestProperty | Struct | |
CfnCapacityProvider.InfrastructureOptimizationProperty | Struct | The configuration that controls how Amazon ECS optimizes your infrastructure. |
CfnCapacityProvider.InstanceLaunchTemplateProperty | Struct | The launch template configuration for Amazon ECS Managed Instances. |
CfnCapacityProvider.InstanceRequirementsRequestProperty | Struct | The instance requirements for attribute-based instance type selection. |
CfnCapacityProvider.ManagedInstancesLocalStorageConfigurationProperty | Struct | |
CfnCapacityProvider.ManagedInstancesNetworkConfigurationProperty | Struct | The network configuration for Amazon ECS Managed Instances. |
CfnCapacityProvider.ManagedInstancesProviderProperty | Struct | The configuration for a Amazon ECS Managed Instances provider. |
CfnCapacityProvider.ManagedInstancesStorageConfigurationProperty | Struct | The storage configuration for Amazon ECS Managed Instances. |
CfnCapacityProvider.ManagedScalingProperty | Struct | The managed scaling settings for the Auto Scaling group capacity provider. |
CfnCapacityProvider.MemoryGiBPerVCpuRequestProperty | Struct | The minimum and maximum amount of memory per vCPU in gibibytes (GiB). |
CfnCapacityProvider.MemoryMiBRequestProperty | Struct | The minimum and maximum amount of memory in mebibytes (MiB) for instance type selection. |
CfnCapacityProvider.NetworkBandwidthGbpsRequestProperty | Struct | The minimum and maximum network bandwidth in gigabits per second (Gbps) for instance type selection. |
CfnCapacityProvider.NetworkInterfaceCountRequestProperty | Struct | The minimum and maximum number of network interfaces for instance type selection. |
CfnCapacityProvider.TotalLocalStorageGBRequestProperty | Struct | The minimum and maximum total local storage in gigabytes (GB) for instance types with local storage. |
CfnCapacityProvider.VCpuCountRangeRequestProperty | Struct | The minimum and maximum number of vCPUs for instance type selection. |
CfnCapacityProviderProps | Struct | Properties for defining a CfnCapacityProvider. |
CfnCluster.CapacityProviderStrategyItemProperty | Struct | The CapacityProviderStrategyItem property specifies the details of the default capacity provider strategy for the cluster. |
CfnCluster.ClusterConfigurationProperty | Struct | The execute command and managed storage configuration for the cluster. |
CfnCluster.ClusterSettingsProperty | Struct | The settings to use when creating a cluster. |
CfnCluster.ExecuteCommandConfigurationProperty | Struct | The details of the execute command configuration. |
CfnCluster.ExecuteCommandLogConfigurationProperty | Struct | The log configuration for the results of the execute command actions. |
CfnCluster.ManagedStorageConfigurationProperty | Struct | The managed storage configuration for the cluster. |
CfnCluster.ServiceConnectDefaultsProperty | Struct | Use this parameter to set a default Service Connect namespace. |
CfnClusterCapacityProviderAssociations.CapacityProviderStrategyProperty | Struct | The CapacityProviderStrategy property specifies the details of the default capacity provider strategy for the cluster. |
CfnClusterCapacityProviderAssociationsProps | Struct | Properties for defining a CfnClusterCapacityProviderAssociations. |
CfnClusterProps | Struct | Properties for defining a CfnCluster. |
CfnDaemon.DaemonAlarmConfigurationProperty | Struct | The CloudWatch alarm configuration for a daemon. |
CfnDaemon.DaemonDeploymentConfigurationProperty | Struct | Optional deployment parameters that control how a daemon rolls out updates across container instances. |
CfnDaemonProps | Struct | Properties for defining a CfnDaemon. |
CfnDaemonTaskDefinition.ContainerDependencyProperty | Struct | The dependencies defined for container startup and shutdown. |
CfnDaemonTaskDefinition.DaemonContainerDefinitionProperty | Struct | A container definition for a daemon task. |
CfnDaemonTaskDefinition.DeviceProperty | Struct | An object representing a container instance host device. |
CfnDaemonTaskDefinition.EnvironmentFileProperty | Struct | A list of files containing the environment variables to pass to a container. |
CfnDaemonTaskDefinition.FirelensConfigurationProperty | Struct | The FireLens configuration for the container. |
CfnDaemonTaskDefinition.HealthCheckProperty | Struct | An object representing a container health check. |
CfnDaemonTaskDefinition.HostVolumePropertiesProperty | Struct | Details on a container instance bind mount host volume. |
CfnDaemonTaskDefinition.KernelCapabilitiesProperty | Struct | The Linux capabilities to add or remove from the default Docker configuration for a container defined in the task definition. |
CfnDaemonTaskDefinition.KeyValuePairProperty | Struct | A key-value pair object. |
CfnDaemonTaskDefinition.LinuxParametersProperty | Struct | The Linux-specific options that are applied to the container, such as Linux KernelCapabilities. |
CfnDaemonTaskDefinition.LogConfigurationProperty | Struct | The log configuration for the container. |
CfnDaemonTaskDefinition.MountPointProperty | Struct | The details for a volume mount point that's used in a container definition. |
CfnDaemonTaskDefinition.RepositoryCredentialsProperty | Struct | The repository credentials for private registry authentication. |
CfnDaemonTaskDefinition.RestartPolicyProperty | Struct | |
CfnDaemonTaskDefinition.SecretProperty | Struct | An object representing the secret to expose to your container. |
CfnDaemonTaskDefinition.SystemControlProperty | Struct | A list of namespaced kernel parameters to set in the container. |
CfnDaemonTaskDefinition.TmpfsProperty | Struct | The container path, mount options, and size of the tmpfs mount. |
CfnDaemonTaskDefinition.UlimitProperty | Struct | The ulimit settings to pass to the container. |
CfnDaemonTaskDefinition.VolumeProperty | Struct | The data volume configuration for tasks launched using this task definition. |
CfnDaemonTaskDefinitionProps | Struct | Properties for defining a CfnDaemonTaskDefinition. |
CfnExpressGatewayService.AutoScalingArnsProperty | Struct | |
CfnExpressGatewayService.ECSManagedResourceArnsProperty | Struct | |
CfnExpressGatewayService.ExpressGatewayContainerProperty | Struct | Defines the configuration for the primary container in an Express service. |
CfnExpressGatewayService.ExpressGatewayRepositoryCredentialsProperty | Struct | The repository credentials for private registry authentication to pass to the container. |
CfnExpressGatewayService.ExpressGatewayScalingTargetProperty | Struct | Defines the auto-scaling configuration for an Express service. |
CfnExpressGatewayService.ExpressGatewayServiceAwsLogsConfigurationProperty | Struct | Specifies the Amazon CloudWatch Logs configuration for the Express service container. |
CfnExpressGatewayService.ExpressGatewayServiceConfigurationProperty | Struct | Represents a specific configuration revision of an Express service, containing all the settings and parameters for that revision. |
CfnExpressGatewayService.ExpressGatewayServiceNetworkConfigurationProperty | Struct | The network configuration for an Express service. |
CfnExpressGatewayService.ExpressGatewayServiceStatusProperty | Struct | An object that defines the status of Express service creation and information about the status of the service. |
CfnExpressGatewayService.IngressPathArnsProperty | Struct | |
CfnExpressGatewayService.IngressPathSummaryProperty | Struct | The entry point into an Express service. |
CfnExpressGatewayService.KeyValuePairProperty | Struct | A key-value pair object. |
CfnExpressGatewayService.SecretProperty | Struct | An object representing the secret to expose to your container. |
CfnExpressGatewayServiceProps | Struct | Properties for defining a CfnExpressGatewayService. |
CfnPrimaryTaskSetProps | Struct | Properties for defining a CfnPrimaryTaskSet. |
CfnService.AdvancedConfigurationProperty | Struct | The advanced settings for a load balancer used in blue/green deployments. |
CfnService.AwsVpcConfigurationProperty | Struct | An object representing the networking details for a task or service. |
CfnService.CanaryConfigurationProperty | Struct | Configuration for a canary deployment strategy that shifts a fixed percentage of traffic to the new service revision, waits for a specified bake time, then shifts the remaining traffic. |
CfnService.CapacityProviderStrategyItemProperty | Struct | The details of a capacity provider strategy. |
CfnService.DeploymentAlarmsProperty | Struct | One 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.DeploymentCircuitBreakerProperty | Struct | > The deployment circuit breaker can only be used for services using the rolling update ( ECS ) deployment type. |
CfnService.DeploymentConfigurationProperty | Struct | Optional deployment parameters that control how many tasks run during a deployment and the ordering of stopping and starting tasks. |
CfnService.DeploymentControllerProperty | Struct | The deployment controller to use for the service. |
CfnService.DeploymentEarlySuccessCriteriaProperty | Struct | |
CfnService.DeploymentLifecycleHookProperty | Struct | A deployment lifecycle hook runs custom logic at specific stages of the deployment process. |
CfnService.EBSTagSpecificationProperty | Struct | The tag specifications of an Amazon EBS volume. |
CfnService.ForceNewDeploymentProperty | Struct | Determines whether to force a new deployment of the service. |
CfnService.HookTimeoutConfigProperty | Struct | |
CfnService.LinearConfigurationProperty | Struct | Configuration 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.LoadBalancerProperty | Struct | The LoadBalancer property specifies details on a load balancer that is used with a service. |
CfnService.LogConfigurationProperty | Struct | The log configuration for the container. |
CfnService.MetricConfigurationProperty | Struct | The configuration for a specific set of metrics to collect for a service. |
CfnService.MonitoringConfigurationProperty | Struct | The optional monitoring configuration for a service, which defines the resolution for the service-level CPUUtilization and MemoryUtilization Amazon CloudWatch metrics. |
CfnService.NetworkConfigurationProperty | Struct | The network configuration for a task or service. |
CfnService.PlacementConstraintProperty | Struct | An object representing a constraint on task placement. |
CfnService.PlacementStrategyProperty | Struct | The task placement strategy for a task or service. |
CfnService.SecretProperty | Struct | An object representing the secret to expose to your container. |
CfnService.ServiceConnectAccessLogConfigurationProperty | Struct | Configuration for Service Connect access logging. |
CfnService.ServiceConnectClientAliasProperty | Struct | Each alias ("endpoint") is a fully-qualified name and port number that other tasks ("clients") can use to connect to this service. |
CfnService.ServiceConnectConfigurationProperty | Struct | The Service Connect configuration of your Amazon ECS service. |
CfnService.ServiceConnectServiceProperty | Struct | The Service Connect service object configuration. |
CfnService.ServiceConnectTestTrafficRulesHeaderProperty | Struct | |
CfnService.ServiceConnectTestTrafficRulesHeaderValueProperty | Struct | |
CfnService.ServiceConnectTestTrafficRulesProperty | Struct | The test traffic routing configuration for Amazon ECS blue/green deployments. |
CfnService.ServiceConnectTlsCertificateAuthorityProperty | Struct | The certificate root authority that secures your service. |
CfnService.ServiceConnectTlsConfigurationProperty | Struct | The key that encrypts and decrypts your resources for Service Connect TLS. |
CfnService.ServiceManagedEBSVolumeConfigurationProperty | Struct | The configuration for the Amazon EBS volume that Amazon ECS creates and manages on your behalf. |
CfnService.ServiceRegistryProperty | Struct | The details for the service registry. |
CfnService.ServiceVolumeConfigurationProperty | Struct | The configuration for a volume specified in the task definition as a volume that is configured at launch time. |
CfnService.ThresholdConfigurationProperty | Struct | Defines the failure threshold that the deployment circuit breaker uses to monitor a deployment. |
CfnService.TimeoutConfigurationProperty | Struct | An object that represents the timeout configurations for Service Connect. |
CfnService.VpcLatticeAdvancedConfigurationProperty | Struct | |
CfnService.VpcLatticeConfigurationProperty | Struct | The VPC Lattice configuration for your service that holds the information for the target group(s) Amazon ECS tasks will be registered to. |
CfnServiceProps | Struct | Properties for defining a CfnService. |
CfnTaskDefinition.AuthorizationConfigProperty | Struct | The authorization configuration details for the Amazon EFS file system. |
CfnTaskDefinition.ContainerDefinitionProperty | Struct | The ContainerDefinition property specifies a container definition. |
CfnTaskDefinition.ContainerDependencyProperty | Struct | The ContainerDependency property specifies the dependencies defined for container startup and shutdown. |
CfnTaskDefinition.DeviceProperty | Struct | The Device property specifies an object representing a container instance host device. |
CfnTaskDefinition.DockerVolumeConfigurationProperty | Struct | The DockerVolumeConfiguration property specifies a Docker volume configuration and is used when you use Docker volumes. |
CfnTaskDefinition.EFSVolumeConfigurationProperty | Struct | This parameter is specified when you're using an Amazon Elastic File System file system for task storage. |
CfnTaskDefinition.EnvironmentFileProperty | Struct | A list of files containing the environment variables to pass to a container. |
CfnTaskDefinition.EphemeralStorageProperty | Struct | The amount of ephemeral storage to allocate for the task. |
CfnTaskDefinition.FirelensConfigurationProperty | Struct | The FireLens configuration for the container. |
CfnTaskDefinition.FSxAuthorizationConfigProperty | Struct | The authorization configuration details for Amazon FSx for Windows File Server file system. |
CfnTaskDefinition.FSxWindowsFileServerVolumeConfigurationProperty | Struct | This parameter is specified when you're using Amazon FSx for Windows File Server file system for task storage. |
CfnTaskDefinition.HealthCheckProperty | Struct | The HealthCheck property specifies an object representing a container health check. |
CfnTaskDefinition.HostEntryProperty | Struct | The 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.HostVolumePropertiesProperty | Struct | The HostVolumeProperties property specifies details on a container instance bind mount host volume. |
CfnTaskDefinition.InferenceAcceleratorProperty | Struct | |
CfnTaskDefinition.KernelCapabilitiesProperty | Struct | The Linux capabilities to add or remove from the default Docker configuration for a container defined in the task definition. |
CfnTaskDefinition.KeyValuePairProperty | Struct | A key-value pair object. |
CfnTaskDefinition.LinuxParametersProperty | Struct | The Linux-specific options that are applied to the container, such as Linux KernelCapabilities . |
CfnTaskDefinition.LogConfigurationProperty | Struct | The LogConfiguration property specifies log configuration options to send to a custom log driver for the container. |
CfnTaskDefinition.MountPointProperty | Struct | The details for a volume mount point that's used in a container definition. |
CfnTaskDefinition.PortMappingProperty | Struct | The PortMapping property specifies a port mapping. |
CfnTaskDefinition.ProxyConfigurationProperty | Struct | The configuration details for the App Mesh proxy. |
CfnTaskDefinition.RepositoryCredentialsProperty | Struct | The repository credentials for private registry authentication. |
CfnTaskDefinition.ResourceRequirementProperty | Struct | The type and amount of a resource to assign to a container. |
CfnTaskDefinition.RestartPolicyProperty | Struct | You can enable a restart policy for each container defined in your task definition, to overcome transient failures faster and maintain task availability. |
CfnTaskDefinition.RuntimePlatformProperty | Struct | Information about the platform for the Amazon ECS service or task. |
CfnTaskDefinition.S3FilesVolumeConfigurationProperty | Struct | This parameter is specified when you're using an Amazon S3 Files file system for task storage. |
CfnTaskDefinition.SecretProperty | Struct | An object representing the secret to expose to your container. |
CfnTaskDefinition.SystemControlProperty | Struct | A list of namespaced kernel parameters to set in the container. |
CfnTaskDefinition.TaskDefinitionPlacementConstraintProperty | Struct | The constraint on task placement in the task definition. |
CfnTaskDefinition.TmpfsProperty | Struct | The container path, mount options, and size of the tmpfs mount. |
CfnTaskDefinition.UlimitProperty | Struct | The ulimit settings to pass to the container. |
CfnTaskDefinition.VolumeFromProperty | Struct | Details on a data volume from another container in the same task definition. |
CfnTaskDefinition.VolumeProperty | Struct | The data volume configuration for tasks launched using this task definition. |
CfnTaskDefinitionProps | Struct | Properties for defining a CfnTaskDefinition. |
CfnTaskSet.AwsVpcConfigurationProperty | Struct | An object representing the networking details for a task or service. |
CfnTaskSet.CapacityProviderStrategyItemProperty | Struct | The details of a capacity provider strategy. |
CfnTaskSet.LoadBalancerProperty | Struct | The load balancer configuration to use with a service or task set. |
CfnTaskSet.NetworkConfigurationProperty | Struct | The network configuration for a task or service. |
CfnTaskSet.ScaleProperty | Struct | A floating-point percentage of the desired number of tasks to place and keep running in the task set. |
CfnTaskSet.ServiceRegistryProperty | Struct | The details for the service registry. |
CfnTaskSetProps | Struct | Properties for defining a CfnTaskSet. |
CloudMapNamespaceOptions | Struct | The options for creating an AWS Cloud Map namespace. |
CloudMapNamespaceOptionsBase | Struct | Options shared by all ways of setting the default AWS Cloud Map namespace of a cluster. |
CloudMapOptions | Struct | The options to enabling AWS Cloud Map for an Amazon ECS service. |
ClusterAttributes | Struct | The properties to import from the ECS cluster. |
ClusterGrants | Facade | Collection of grant methods for a IClusterRef. |
ClusterProps | Struct | The properties used to define an ECS cluster. |
CommonTaskDefinitionAttributes | Struct | The common task definition attributes used across all types of task definitions. |
CommonTaskDefinitionProps | Struct | The common properties for all task definitions. |
Compatibility | Enum | The task launch type compatibility requirement. |
ContainerDefinition | Construct | A container definition is used in a task definition to describe the containers that are launched as part of a task. |
ContainerDefinitionOptions | Struct | |
ContainerDefinitionProps | Struct | The properties in a container definition. |
ContainerDependency | Struct | The details of a dependency on another container in the task definition. |
ContainerDependencyCondition | Enum | |
ContainerImage | Class | Constructs for types of container images. |
ContainerImageConfig | Struct | The configuration for creating a container image. |
ContainerInsights | Enum | The CloudWatch Container Insights setting. |
ContainerMountPoint | Struct | Defines the mount point details for attaching a volume to a container. |
CpuArchitecture | Class | The CpuArchitecture for Fargate Runtime Platform. |
CpuUtilizationScalingProps | Struct | The properties for enabling scaling based on CPU utilization. |
CredentialSpec | Class | Base construct for a credential specification (CredSpec). |
CredentialSpecConfig | Struct | Configuration for a credential specification (CredSpec) used for a ECS container. |
DeploymentAlarmConfig | Struct | Configuration for deployment alarms. |
DeploymentAlarmOptions | Struct | Options for deployment alarms. |
DeploymentCircuitBreaker | Struct | The deployment circuit breaker to use for the service. |
DeploymentController | Struct | The deployment controller to use for the service. |
DeploymentControllerType | Enum | The deployment controller type to use for the service. |
DeploymentLifecycleHookTargetConfig | Struct | Configuration for a deployment lifecycle hook target. |
DeploymentLifecycleLambdaTarget | Class | Use an AWS Lambda function as a deployment lifecycle hook target. |
DeploymentLifecycleLambdaTargetProps | Struct | Configuration for a lambda deployment lifecycle hook. |
DeploymentLifecycleStage | Enum | Deployment lifecycle stages where hooks can be executed. |
DeploymentStrategy | Enum | The deployment stratergy to use for ECS controller. |
Device | Struct | A container instance host device. |
DevicePermission | Enum | Permissions for device access. |
DockerVolumeConfiguration | Struct | The configuration for a Docker volume. |
DomainJoinedCredentialSpec | Class | Credential specification (CredSpec) file. |
DomainlessCredentialSpec | Class | Credential specification for domainless gMSA. |
EbsPropagatedTagSource | Enum | Propagate tags for EBS Volume Configuration from either service or task definition. |
EBSTagSpecification | Struct | Tag Specification for EBS volume. |
Ec2ServiceAttributes | Struct | The properties to import from the service using the EC2 launch type. |
Ec2ServiceProps | Struct | The properties for defining a service using the EC2 launch type. |
Ec2TaskDefinitionAttributes | Struct | Attributes used to import an existing EC2 task definition. |
Ec2TaskDefinitionProps | Struct | The properties for a task definition run on an EC2 cluster. |
EcrImage | Class | An image from an Amazon ECR repository. |
EcsOptimizedImage | Class | Construct a Linux or Windows machine image from the latest ECS Optimized AMI published in SSM. |
EcsOptimizedImageOptions | Struct | Additional configuration properties for EcsOptimizedImage factory functions. |
EcsTarget | Struct | |
EfsVolumeConfiguration | Struct | The configuration for an Elastic FileSystem volume. |
EnvironmentFile | Class | Constructs for types of environment files. |
EnvironmentFileConfig | Struct | Configuration for the environment file. |
EnvironmentFileType | Enum | Type of environment file to be included in the container definition. |
ExecuteCommandConfiguration | Struct | The details of the execute command configuration. |
ExecuteCommandLogConfiguration | Struct | The log configuration for the results of the execute command actions. |
ExecuteCommandLogging | Enum | The log settings to use to for logging the execute command session. |
ExistingCloudMapNamespaceOptions | Struct | The options for using an existing AWS Cloud Map namespace as the default namespace of a cluster. |
ExternalServiceAttributes | Struct | The properties to import from the service using the External launch type. |
ExternalServiceProps | Struct | The properties for defining a service using the External launch type. |
ExternalTaskDefinitionAttributes | Struct | Attributes used to import an existing External task definition. |
ExternalTaskDefinitionProps | Struct | The properties for a task definition run on an External cluster. |
FargatePlatformVersion | Enum | The platform version on which to run your service. |
FargateServiceAttributes | Struct | The properties to import from the service using the Fargate launch type. |
FargateServiceProps | Struct | The properties for defining a service using the Fargate launch type. |
FargateTaskDefinitionAttributes | Struct | Attributes used to import an existing Fargate task definition. |
FargateTaskDefinitionProps | Struct | The properties for a task definition. |
FileSystemType | Enum | FileSystemType for Service Managed EBS Volume Configuration. |
FirelensConfig | Struct | Firelens Configuration https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_firelens.html#firelens-taskdef. |
FirelensConfigFileType | Enum | Firelens configuration file type, s3 or file path. |
FireLensLogDriver | Class | FireLens enables you to use task definition parameters to route logs to an AWS service or AWS Partner Network (APN) destination for log storage and analytics. |
FireLensLogDriverProps | Struct | Specifies the firelens log driver configuration options. |
FirelensLogRouter | Construct | Firelens log router. |
FirelensLogRouterDefinitionOptions | Struct | The options for creating a firelens log router. |
FirelensLogRouterProps | Struct | The properties in a firelens log router. |
FirelensLogRouterType | Enum | Firelens log router type, fluentbit or fluentd. |
FirelensOptions | Struct | The options for firelens log router https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_firelens.html#firelens-taskdef-customconfig. |
FluentdLogDriver | Class | A log driver that sends log information to journald Logs. |
FluentdLogDriverProps | Struct | Specifies the fluentd log driver configuration options. |
ForceNewDeployment | Struct | Configuration for forcing a new deployment of the service. |
GelfCompressionType | Enum | The type of compression the GELF driver uses to compress each log message. |
GelfLogDriver | Class | A log driver that sends log information to journald Logs. |
GelfLogDriverProps | Struct | Specifies the journald log driver configuration options. |
GenericLogDriver | Class | A log driver that sends logs to the specified driver. |
GenericLogDriverProps | Struct | The configuration to use when creating a log driver. |
HealthCheck | Struct | The health check command and associated configuration parameters for the container. |
Host | Struct | The details on a container instance bind mount host volume. |
IAlternateTarget | Interface | Interface for configuring alternate target groups for blue/green deployments. |
IBaseService | Interface | The interface for BaseService. |
ICluster | Interface | A regional grouping of one or more container instances on which you can run tasks and services. |
IDeploymentLifecycleHookTarget | Interface | Interface for deployment lifecycle hook targets. |
IEc2Service | Interface | The interface for a service using the EC2 launch type on an ECS cluster. |
IEc2TaskDefinition | Interface | The interface of a task definition run on an EC2 cluster. |
IEcsLoadBalancerTarget | Interface | Interface for ECS load balancer target. |
IExternalService | Interface | The interface for a service using the External launch type on an ECS cluster. |
IExternalTaskDefinition | Interface | The interface of a task definition run on an External cluster. |
IFargateService | Interface | The interface for a service using the Fargate launch type on an ECS cluster. |
IFargateTaskDefinition | Interface | The interface of a task definition run on a Fargate cluster. |
InferenceAccelerator | Struct | Elastic Inference Accelerator. |
InstanceMonitoring | Enum | The monitoring configuration for EC2 instances. |
IpcMode | Enum | The IPC resource namespace to use for the containers in the task. |
IService | Interface | The interface for a service. |
ITaskDefinition | Interface | The interface for all task definitions. |
ITaskDefinitionExtension | Interface | An extension for Task Definitions. |
JournaldLogDriver | Class | A log driver that sends log information to journald Logs. |
JournaldLogDriverProps | Struct | Specifies the journald log driver configuration options. |
JsonFileLogDriver | Class | A log driver that sends log information to json-file Logs. |
JsonFileLogDriverProps | Struct | Specifies the json-file log driver configuration options. |
LaunchType | Enum | The launch type of an ECS service. |
LinuxParameters | Construct | Linux-specific options that are applied to the container. |
LinuxParametersProps | Struct | The properties for defining Linux-specific options that are applied to the container. |
ListenerConfig | Class | Base class for configuring listener when registering targets. |
ListenerRuleConfiguration | Class | Represents a listener configuration for advanced load balancer settings. |
LoadBalancerTargetOptions | Struct | Properties for defining an ECS target. |
LogDriver | Class | The base class for log drivers. |
LogDriverConfig | Struct | The configuration to use when creating a log driver. |
LogDrivers | Class | The base class for log drivers. |
MachineImageType | Enum | The machine image type. |
ManagedInstancesCapacityProvider | Construct | A Managed Instances Capacity Provider. |
ManagedInstancesCapacityProviderProps | Struct | The options for creating a Managed Instances Capacity Provider. |
ManagedStorageConfiguration | Struct | Kms Keys for encryption ECS managed storage. |
MemoryUtilizationScalingProps | Struct | The properties for enabling scaling based on memory utilization. |
MountPoint | Struct | The details of data volume mount points for a container. |
NetworkMode | Enum | The networking mode to use for the containers in the task. |
NoneLogDriver | Class | A log driver that sets the log driver to none (no logs collected). |
OperatingSystemFamily | Class | The operating system for Fargate Runtime Platform. |
PidMode | Enum | The process namespace to use for the containers in the task. |
PlacementConstraint | Class | The placement constraints to use for tasks in the service. For more information, see Amazon ECS Task Placement Constraints. |
PlacementStrategy | Class | The placement strategies to use for tasks in the service. For more information, see Amazon ECS Task Placement Strategies. |
PortMap | Class | PortMap ValueObjectClass having by ContainerDefinition. |
PortMapping | Struct | Port mappings allow containers to access ports on the host container instance to send or receive traffic. |
PropagatedTagSource | Enum | Propagate tags from either service or task definition. |
PropagateManagedInstancesTags | Enum | Propagate tags for Managed Instances. |
Protocol | Enum | Network protocol. |
ProxyConfiguration | Class | The base class for proxy configurations. |
ProxyConfigurations | Class | The base class for proxy configurations. |
RepositoryImage | Class | An image hosted in a public or private repository. |
RepositoryImageProps | Struct | The properties for an image hosted in a public or private repository. |
RequestCountScalingProps | Struct | The properties for enabling scaling based on Application Load Balancer (ALB) request counts. |
RuntimePlatform | Struct | The interface for Runtime Platform. |
S3EnvironmentFile | Class | Environment file from S3. |
ScalableTaskCount | Construct | The scalable attribute representing task count. |
ScalableTaskCountProps | Struct | The properties of a scalable attribute representing task count. |
Scope | Enum | The scope for the Docker volume that determines its lifecycle. |
ScratchSpace | Struct | The temporary disk space mounted to the container. |
Secret | Class | A secret environment variable. |
SecretVersionInfo | Struct | Specify the secret's version id or version stage. |
ServiceConnect | Class | ServiceConnect ValueObjectClass having by ContainerDefinition. |
ServiceConnectAccessLogConfiguration | Struct | Configuration for Service Connect access logs. |
ServiceConnectAccessLogFormat | Enum | The format of Service Connect access logs. |
ServiceConnectProps | Struct | Interface for Service Connect configuration. |
ServiceConnectService | Struct | Interface for service connect Service props. |
ServiceConnectTlsConfiguration | Struct | TLS configuration for Service Connect service. |
ServiceManagedEBSVolumeConfiguration | Struct | Represents the configuration for an ECS Service managed EBS volume. |
ServiceManagedVolume | Construct | Represents a service-managed volume and always configured at launch. |
ServiceManagedVolumeProps | Struct | Represents the Volume configuration for an ECS service. |
SplunkLogDriver | Class | A log driver that sends log information to splunk Logs. |
SplunkLogDriverProps | Struct | Specifies the splunk log driver configuration options. |
SplunkLogFormat | Enum | Log Message Format. |
SyslogLogDriver | Class | A log driver that sends log information to syslog Logs. |
SyslogLogDriverProps | Struct | Specifies the syslog log driver configuration options. |
SystemControl | Struct | Kernel parameters to set in the container. |
TagParameterContainerImage | Class | A 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. |
TagParameterContainerImageProps | Struct | Properties for TagParameterContainerImage. |
TaskDefinitionAttributes | Struct | A reference to an existing task definition. |
TaskDefinitionProps | Struct | The properties for task definitions. |
TaskDefinitionRevision | Class | Represents revision of a task definition, either a specific numbered revision or the latest revision. |
Tmpfs | Struct | The details of a tmpfs mount for a container. |
TmpfsMountOption | Enum | The supported options for a tmpfs mount for a container. |
TrackCustomMetricProps | Struct | The properties for enabling target tracking scaling based on a custom CloudWatch metric. |
TrafficShiftConfig | Struct | Configuration for traffic shift during progressive deployments. |
Ulimit | Struct | The ulimit settings to pass to the container. |
UlimitName | Enum | Type of resource to set a limit on. |
VersionConsistency | Enum | State of the container version consistency feature. |
Volume | Struct | A data volume used in a task definition. |
VolumeFrom | Struct | The details on a data volume from another container in the same task definition. |
WindowsOptimizedVersion | Enum | ECS-optimized Windows version list. |