Namespace Amazon.CDK.AWS.ECS
Amazon ECS Construct Library
This package contains constructs for working with Amazon Elastic Container Service (Amazon ECS).
Amazon Elastic Container Service (Amazon ECS) is a fully managed container orchestration service.
For further information on Amazon ECS, see the Amazon ECS documentation
The following example creates an Amazon ECS cluster, adds capacity to it, and runs a service on it:
Vpc vpc;
// Create an ECS cluster
var cluster = new Cluster(this, "Cluster", new ClusterProps { Vpc = vpc });
// Add capacity to it
cluster.AddCapacity("DefaultAutoScalingGroupCapacity", new AddCapacityOptions {
InstanceType = new InstanceType("t2.xlarge"),
DesiredCapacity = 3
});
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
});
For a set of constructs defining common ECS architectural patterns, see the aws-cdk-lib/aws-ecs-patterns
package.
Launch Types: AWS Fargate vs Amazon EC2 vs AWS ECS Anywhere
There are three sets of constructs in this library:
Here are the main differences:
For more information on Amazon EC2 vs AWS Fargate, networking and ECS Anywhere see the AWS Documentation: AWS Fargate, Task Networking, ECS Anywhere
Clusters
A Cluster
defines the infrastructure to run your
tasks on. You can run many tasks on a single cluster.
The following code creates a cluster that can run AWS Fargate tasks:
Vpc vpc;
var cluster = new Cluster(this, "Cluster", new ClusterProps {
Vpc = vpc
});
The following code imports an existing cluster using the ARN which can be used to import an Amazon ECS service either EC2 or Fargate.
var clusterArn = "arn:aws:ecs:us-east-1:012345678910:cluster/clusterName";
var cluster = Cluster.FromClusterArn(this, "Cluster", clusterArn);
To use tasks with Amazon EC2 launch-type, you have to add capacity to the cluster in order for tasks to be scheduled on your instances. Typically, you add an AutoScalingGroup with instances running the latest Amazon ECS-optimized AMI to the cluster. There is a method to build and add such an AutoScalingGroup automatically, or you can supply a customized AutoScalingGroup that you construct yourself. It's possible to add multiple AutoScalingGroups with various instance types.
The following example creates an Amazon ECS cluster and adds capacity to it:
Vpc vpc;
var cluster = new Cluster(this, "Cluster", new ClusterProps {
Vpc = vpc
});
// Either add default capacity
cluster.AddCapacity("DefaultAutoScalingGroupCapacity", new AddCapacityOptions {
InstanceType = new InstanceType("t2.xlarge"),
DesiredCapacity = 3
});
// 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);
If you omit the property vpc
, the construct will create a new VPC with two AZs.
By default, all machine images will auto-update to the latest version on each deployment, causing a replacement of the instances in your AutoScalingGroup if the AMI has been updated since the last deployment.
If task draining is enabled, ECS will transparently reschedule tasks on to the new
instances before terminating your old instances. If you have disabled task draining,
the tasks will be terminated along with the instance. To prevent that, you
can pick a non-updating AMI by passing cacheInContext: true
, but be sure
to periodically update to the latest AMI manually by using the CDK CLI
context management commands:
Vpc vpc;
var autoScalingGroup = new AutoScalingGroup(this, "ASG", new AutoScalingGroupProps {
MachineImage = EcsOptimizedImage.AmazonLinux(new EcsOptimizedImageOptions { CachedInContext = true }),
Vpc = vpc,
InstanceType = new InstanceType("t2.micro")
});
To use LaunchTemplate
with AsgCapacityProvider
, make sure to specify the userData
in the LaunchTemplate
:
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);
The following code retrieve the Amazon Resource Names (ARNs) of tasks that are a part of a specified ECS cluster. It's useful when you want to grant permissions to a task to access other AWS resources.
Cluster cluster;
TaskDefinition taskDefinition;
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 }
}));
To manage task protection settings in an ECS cluster, you can use the grantTaskProtection
method.
This method grants the ecs:UpdateTaskProtection
permission to a specified IAM entity.
// Assume 'cluster' is an instance of ecs.Cluster
Cluster cluster;
Role taskRole;
// Grant ECS Task Protection permissions to the role
// Now 'taskRole' has the 'ecs:UpdateTaskProtection' permission on all tasks in the cluster
cluster.GrantTaskProtection(taskRole);
Bottlerocket
Bottlerocket is a Linux-based open source operating system that is purpose-built by AWS for running containers. You can launch Amazon ECS container instances with the Bottlerocket AMI.
The following example will create a capacity with self-managed Amazon EC2 capacity of 2 c5.large
Linux instances running with Bottlerocket
AMI.
The following example adds Bottlerocket capacity to the cluster:
Cluster cluster;
cluster.AddCapacity("bottlerocket-asg", new AddCapacityOptions {
MinCapacity = 2,
InstanceType = new InstanceType("c5.large"),
MachineImage = new BottleRocketImage()
});
You can also specify an NVIDIA-compatible AMI such as in this example:
Cluster cluster;
cluster.AddCapacity("bottlerocket-asg", new AddCapacityOptions {
InstanceType = new InstanceType("p3.2xlarge"),
MachineImage = new BottleRocketImage(new BottleRocketImageProps {
Variant = BottlerocketEcsVariant.AWS_ECS_2_NVIDIA
})
});
ARM64 (Graviton) Instances
To launch instances with ARM64 hardware, you can use the Amazon ECS-optimized Amazon Linux 2 (arm64) AMI. Based on Amazon Linux 2, this AMI is recommended for use when launching your EC2 instances that are powered by Arm-based AWS Graviton Processors.
Cluster cluster;
cluster.AddCapacity("graviton-cluster", new AddCapacityOptions {
MinCapacity = 2,
InstanceType = new InstanceType("c6g.large"),
MachineImage = EcsOptimizedImage.AmazonLinux2(AmiHardwareType.ARM)
});
Bottlerocket is also supported:
Cluster cluster;
cluster.AddCapacity("graviton-cluster", new AddCapacityOptions {
MinCapacity = 2,
InstanceType = new InstanceType("c6g.large"),
MachineImageType = MachineImageType.BOTTLEROCKET
});
Amazon Linux 2 (Neuron) Instances
To launch Amazon EC2 Inf1, Trn1 or Inf2 instances, you can use the Amazon ECS optimized Amazon Linux 2 (Neuron) AMI. It comes pre-configured with AWS Inferentia and AWS Trainium drivers and the AWS Neuron runtime for Docker which makes running machine learning inference workloads easier on Amazon ECS.
Cluster cluster;
cluster.AddCapacity("neuron-cluster", new AddCapacityOptions {
MinCapacity = 2,
InstanceType = new InstanceType("inf1.xlarge"),
MachineImage = EcsOptimizedImage.AmazonLinux2(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.
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
});
SNS Topic Encryption
When the ecs.AddCapacityOptions
that you provide has a non-zero taskDrainTime
(the default) then an SNS topic and Lambda are created to ensure that the
cluster's instances have been properly drained of tasks before terminating. The SNS Topic is sent the instance-terminating lifecycle event from the AutoScalingGroup,
and the Lambda acts on that event. If you wish to engage server-side encryption for this SNS Topic
then you may do so by providing a KMS key for the topicEncryptionKey
property of ecs.AddCapacityOptions
.
// Given
Cluster cluster;
Key key;
// Then, use that key to encrypt the lifecycle-event SNS Topic.
cluster.AddCapacity("ASGEncryptedSNS", new AddCapacityOptions {
InstanceType = new InstanceType("t2.xlarge"),
DesiredCapacity = 3,
TopicEncryptionKey = key
});
Task definitions
A task definition describes what a single copy of a task should look like. A task definition has one or more containers; typically, it has one main container (the default container is the first one that's added to the task definition, and it is marked essential) and optionally some supporting containers which are used to support the main container, doings things like upload logs or metrics to monitoring services.
To run a task or service with Amazon EC2 launch type, use the Ec2TaskDefinition
. For AWS Fargate tasks/services, use the
FargateTaskDefinition
. For AWS ECS Anywhere use the ExternalTaskDefinition
. These classes
provide simplified APIs that only contain properties relevant for each specific launch type.
For a FargateTaskDefinition
, specify the task size (memoryLimitMiB
and cpu
):
var fargateTaskDefinition = new FargateTaskDefinition(this, "TaskDef", new FargateTaskDefinitionProps {
MemoryLimitMiB = 512,
Cpu = 256
});
On Fargate Platform Version 1.4.0 or later, you may specify up to 200GiB of ephemeral storage:
var fargateTaskDefinition = new FargateTaskDefinition(this, "TaskDef", new FargateTaskDefinitionProps {
MemoryLimitMiB = 512,
Cpu = 256,
EphemeralStorageGiB = 100
});
To specify the process namespace to use for the containers in the task, use the pidMode
property:
var fargateTaskDefinition = new FargateTaskDefinition(this, "TaskDef", new FargateTaskDefinitionProps {
RuntimePlatform = new RuntimePlatform {
OperatingSystemFamily = OperatingSystemFamily.LINUX,
CpuArchitecture = CpuArchitecture.ARM64
},
MemoryLimitMiB = 512,
Cpu = 256,
PidMode = 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()
:
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")
});
For an Ec2TaskDefinition
:
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
});
For an ExternalTaskDefinition
:
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
});
You can specify container properties when you add them to the task definition, or with various methods, e.g.:
To add a port mapping when adding a container to the task definition, specify the portMappings
option:
TaskDefinition taskDefinition;
taskDefinition.AddContainer("WebContainer", new ContainerDefinitionOptions {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
MemoryLimitMiB = 1024,
PortMappings = new [] { new PortMapping { ContainerPort = 3000 } }
});
To add port mappings directly to a container definition, call addPortMappings()
:
ContainerDefinition container;
container.AddPortMappings(new PortMapping {
ContainerPort = 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.
ContainerDefinition container;
container.AddPortMappings(new PortMapping {
ContainerPort = ContainerDefinition.CONTAINER_PORT_USE_RANGE,
ContainerPortRange = "8080-8081"
});
To add data volumes to a task definition, call addVolume()
:
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);
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:
var taskDefinition = new TaskDefinition(this, "TaskDef", new TaskDefinitionProps {
MemoryMiB = "512",
Cpu = "256",
NetworkMode = NetworkMode.AWS_VPC,
Compatibility = Compatibility.EC2_AND_FARGATE
});
To grant a principal permission to run your TaskDefinition
, you can use the TaskDefinition.grantRun()
method:
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);
To deploy containerized applications that require the allocation of standard input (stdin) or a terminal (tty), use the interactive
property.
This parameter corresponds to OpenStdin
in the Create a container section of the Docker Remote API
and the --interactive
option to docker run.
TaskDefinition taskDefinition;
taskDefinition.AddContainer("Container", new ContainerDefinitionOptions {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
Interactive = true
});
Images
Images supply the software that runs inside the container. Images can be obtained from either DockerHub or from ECR repositories, built directly from a local Dockerfile, or use an existing tarball.
Environment variables
To pass environment variables to the container, you can use the environment
, environmentFiles
, and secrets
props.
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"));
The task execution role is automatically granted read permissions on the secrets/parameters. Further details provided in the AWS documentation about specifying environment variables.
Linux parameters
To apply additional linux-specific options related to init process and memory management to the container, use the linuxParameters
property:
TaskDefinition taskDefinition;
taskDefinition.AddContainer("container", 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
})
});
System controls
To set system controls (kernel parameters) on the container, use the systemControls
prop:
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"
} }
});
Docker labels
You can add labels to the container with the dockerLabels
property or with the addDockerLabel
method:
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");
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
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")
});
Using Windows authentication with gMSA
Amazon ECS supports Active Directory authentication for Linux containers through a special kind of service account called a group Managed Service Account (gMSA). For more details, please see the product documentation on how to implement on Windows containers, or this blog post on how to implement on Linux containers.
There are two types of CredentialSpecs, domained-join or domainless. Both types support creation from a S3 bucket, a SSM parameter, or by directly specifying a location for the file in the constructor.
A domian-joined gMSA container looks like:
// Make sure the task definition's execution role has permissions to read from the S3 bucket or SSM parameter where the CredSpec file is stored.
IParameter parameter;
TaskDefinition taskDefinition;
// Domain-joined gMSA container from a SSM parameter
taskDefinition.AddContainer("gmsa-domain-joined-container", new ContainerDefinitionOptions {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
Cpu = 128,
MemoryLimitMiB = 256,
CredentialSpecs = new [] { 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.
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") }
});
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.
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")
});
Service
A Service
instantiates a TaskDefinition
on a Cluster
a given number of
times, optionally associating them with a load balancer.
If a task fails,
Amazon ECS automatically restarts the task.
Cluster cluster;
TaskDefinition taskDefinition;
var service = new FargateService(this, "Service", new FargateServiceProps {
Cluster = cluster,
TaskDefinition = taskDefinition,
DesiredCount = 5
});
ECS Anywhere service definition looks like:
Cluster cluster;
TaskDefinition taskDefinition;
var service = new ExternalService(this, "Service", new ExternalServiceProps {
Cluster = cluster,
TaskDefinition = taskDefinition,
DesiredCount = 5
});
Services
by default will create a security group if not provided.
If you'd like to specify which security groups to use you can override the securityGroups
property.
By default, the service will use the revision of the passed task definition generated when the TaskDefinition
is deployed by CloudFormation. However, this may not be desired if the revision is externally managed,
for example through CodeDeploy.
To set a specific revision number or the special latest
revision, use the taskDefinitionRevision
parameter:
Cluster cluster;
TaskDefinition taskDefinition;
new ExternalService(this, "Service", new ExternalServiceProps {
Cluster = cluster,
TaskDefinition = taskDefinition,
DesiredCount = 5,
TaskDefinitionRevision = TaskDefinitionRevision.Of(1)
});
new ExternalService(this, "Service", new ExternalServiceProps {
Cluster = cluster,
TaskDefinition = taskDefinition,
DesiredCount = 5,
TaskDefinitionRevision = 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.
Cluster cluster;
TaskDefinition taskDefinition;
var service = new FargateService(this, "Service", new FargateServiceProps {
Cluster = cluster,
TaskDefinition = taskDefinition,
CircuitBreaker = new DeploymentCircuitBreaker {
Enable = true,
Rollback = 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.
using Amazon.CDK.AWS.CloudWatch;
Cluster cluster;
TaskDefinition taskDefinition;
Alarm elbAlarm;
var service = new FargateService(this, "Service", new FargateServiceProps {
Cluster = cluster,
TaskDefinition = taskDefinition,
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
});
Note: Deployment alarms are only available when <code>deploymentController</code> is set
to <code>DeploymentControllerType.ECS</code>, 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.
Option 1, defining a physical name for the alarm:
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
});
Option 2, defining a physical name for the service:
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
});
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
});
This issue only applies if the metrics to alarm on are emitted by the service itself. If the metrics are emitted by a different resource, that does not depend on the service, there will be no restrictions on the alarm name.
Include an application/network load balancer
Services
are load balancing targets and can be added to a target group, which will be attached to an application/network load balancers:
Vpc vpc;
Cluster cluster;
TaskDefinition taskDefinition;
var service = new FargateService(this, "Service", new FargateServiceProps { Cluster = cluster, TaskDefinition = taskDefinition });
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
}) }
});
Note: ECS Anywhere doesn't support application/network load balancers.
Note that in the example above, the default service
only allows you to register the first essential container or the first mapped port on the container as a target and add it to a new target group. To have more control over which container and port to register as targets, you can use service.loadBalancerTarget()
to return a load balancing target for a specific container and port.
Alternatively, you can also create all load balancer targets to be registered in this service, add them to target groups, and attach target groups to listeners accordingly.
Cluster cluster;
TaskDefinition taskDefinition;
Vpc vpc;
var service = new FargateService(this, "Service", new FargateServiceProps { Cluster = cluster, TaskDefinition = taskDefinition });
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
})
});
Using a Load Balancer from a different Stack
If you want to put your Load Balancer and the Service it is load balancing to in
different stacks, you may not be able to use the convenience methods
loadBalancer.addListener()
and listener.addTargets()
.
The reason is that these methods will create resources in the same Stack as the
object they're called on, which may lead to cyclic references between stacks.
Instead, you will have to create an ApplicationListener
in the service stack,
or an empty TargetGroup
in the load balancer stack that you attach your
service to.
See the ecs/cross-stack-load-balancer example for the alternatives.
Include a classic load balancer
Services
can also be directly attached to a classic load balancer as targets:
Cluster cluster;
TaskDefinition taskDefinition;
Vpc vpc;
var service = new Ec2Service(this, "Service", new Ec2ServiceProps { Cluster = cluster, TaskDefinition = taskDefinition });
var lb = new LoadBalancer(this, "LB", new LoadBalancerProps { Vpc = vpc });
lb.AddListener(new LoadBalancerListener { ExternalPort = 80 });
lb.AddTarget(service);
Similarly, if you want to have more control over load balancer targeting:
Cluster cluster;
TaskDefinition taskDefinition;
Vpc vpc;
var service = new Ec2Service(this, "Service", new Ec2ServiceProps { Cluster = cluster, TaskDefinition = taskDefinition });
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
}));
There are two higher-level constructs available which include a load balancer for you that can be found in the aws-ecs-patterns module:
Import existing services
Ec2Service
and FargateService
provide methods to import existing EC2/Fargate services.
The ARN of the existing service has to be specified to import the service.
Since AWS has changed the ARN format for ECS,
feature flag @aws-cdk/aws-ecs:arnFormatIncludesClusterName
must be enabled to use the new ARN format.
The feature flag changes behavior for the entire CDK project. Therefore it is not possible to mix the old and the new format in one CDK project.
declare const cluster: ecs.Cluster;
// Import service from EC2 service attributes
const service = ecs.Ec2Service.fromEc2ServiceAttributes(this, 'EcsService', {
serviceArn: 'arn:aws:ecs:us-west-2:123456789012:service/my-http-service',
cluster,
});
// Import service from EC2 service ARN
const service = ecs.Ec2Service.fromEc2ServiceArn(this, 'EcsService', 'arn:aws:ecs:us-west-2:123456789012:service/my-http-service');
// Import service from Fargate service attributes
const service = ecs.FargateService.fromFargateServiceAttributes(this, 'EcsService', {
serviceArn: 'arn:aws:ecs:us-west-2:123456789012:service/my-http-service',
cluster,
});
// Import service from Fargate service ARN
const service = ecs.FargateService.fromFargateServiceArn(this, 'EcsService', 'arn:aws:ecs:us-west-2:123456789012:service/my-http-service');
Task Auto-Scaling
You can configure the task count of a service to match demand. Task auto-scaling is
configured by calling autoScaleTaskCount()
:
ApplicationTargetGroup target;
BaseService service;
var scaling = service.AutoScaleTaskCount(new EnableScalingProps { MaxCapacity = 10 });
scaling.ScaleOnCpuUtilization("CpuScaling", new CpuUtilizationScalingProps {
TargetUtilizationPercent = 50
});
scaling.ScaleOnRequestCount("RequestScaling", new RequestCountScalingProps {
RequestsPerTarget = 10000,
TargetGroup = target
});
Task auto-scaling is powered by Application Auto-Scaling. See that section for details.
Integration with CloudWatch Events
To start an Amazon ECS task on an Amazon EC2-backed Cluster, instantiate an
aws-cdk-lib/aws-events-targets.EcsTask
instead of an Ec2Service
:
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 min)")
});
// 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"
} }
} }
}));
Log Drivers
Currently Supported Log Drivers:
awslogs Log Driver
// 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)
})
});
fluentd Log Driver
// 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()
});
gelf Log Driver
// 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" })
});
journald Log Driver
// 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()
});
json-file Log Driver
// 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()
});
splunk Log Driver
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"
})
});
syslog Log Driver
// 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()
});
firelens Log Driver
// 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" }
}
})
});
To pass secrets to the log configuration, use the secretOptions
property of the log configuration. The task execution role is automatically granted read permissions on the secrets/parameters.
Secret secret;
StringParameter parameter;
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) } }
})
});
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.
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" }
}
})
});
Visit <a href="https://docs.fluentbit.io/manual/pipeline/outputs/cloudwatch#configuration-parameters">Fluent Bit CloudWatch Configuration Parameters</a>
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
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" }
}
})
});
CloudMap Service Discovery
To register your ECS service with a CloudMap Service Registry, you may add the
cloudMapOptions
property to your service:
TaskDefinition taskDefinition;
Cluster cluster;
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
}
});
With bridge
or host
network modes, only SRV
DNS record types are supported.
By default, SRV
DNS record types will target the default container and default
port. However, you may target a different container and port on the same ECS task:
TaskDefinition taskDefinition;
Cluster cluster;
// Add a container to the task definition
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,
CloudMapOptions = new CloudMapOptions {
// Create SRV records - useful for bridge networking
DnsRecordType = DnsRecordType.SRV,
// Targets port TCP port 7600 `specificContainer`
Container = specificContainer,
ContainerPort = 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:
Service cloudMapService;
FargateService ecsService;
ecsService.AssociateCloudMapService(new AssociateCloudMapServiceOptions {
Service = cloudMapService
});
Capacity Providers
There are two major families of Capacity Providers: AWS Fargate (including Fargate Spot) and EC2 Auto Scaling Group Capacity Providers. Both are supported.
Fargate Capacity Providers
To enable Fargate capacity providers, you can either set
enableFargateCapacityProviders
to true
when creating your cluster, or by
invoking the enableFargateCapacityProviders()
method after creating your
cluster. This will add both FARGATE
and FARGATE_SPOT
as available capacity
providers on your cluster.
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,
CapacityProviderStrategies = new [] { new CapacityProviderStrategy {
CapacityProvider = "FARGATE_SPOT",
Weight = 2
}, new CapacityProviderStrategy {
CapacityProvider = "FARGATE",
Weight = 1
} }
});
Auto Scaling Group Capacity Providers
To add an Auto Scaling Group Capacity Provider, first create an EC2 Auto Scaling
Group. Then, create an AsgCapacityProvider
and pass the Auto Scaling Group to
it in the constructor. Then add the Capacity Provider to the cluster. Finally,
you can refer to the Provider by its name in your service's or task's Capacity
Provider strategy.
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 <a href="https://github.com/aws/containers-roadmap/issues/631">CloudFormation issue</a>
that prevents CloudFormation from automatically deleting Auto Scaling Groups that
have Managed Termination Protection enabled. To work around this issue you could set
enableManagedTerminationProtection
to false
on the Auto Scaling Group Capacity
Provider. If you'd rather not disable Managed Termination Protection, you can manually
delete the Auto Scaling Group.
For other workarounds, see this GitHub issue.
Managed instance draining facilitates graceful termination of Amazon ECS instances. This allows your service workloads to stop safely and be rescheduled to non-terminating instances. Infrastructure maintenance and updates are preformed without disruptions to workloads. To use managed instance draining, set enableManagedDraining to true.
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,
CapacityProviderStrategies = new [] { new CapacityProviderStrategy {
CapacityProvider = capacityProvider.CapacityProviderName,
Weight = 1
} }
});
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 weight
s of each capacity provider determine how tasks are distributed after base
is satisfied.
You can associate a default capacity provider strategy with an Amazon ECS cluster. After you do this, a default capacity provider strategy is used when creating a service or running a standalone task in the cluster and whenever a custom capacity provider strategy or a launch type isn't specified. We recommend that you define a default capacity provider strategy for each cluster.
For more information visit https://docs.aws.amazon.com/AmazonECS/latest/developerguide/cluster-capacity-providers.html
When the service does not have a capacity provider strategy, the cluster's default capacity provider strategy will be used. Default Capacity Provider Strategy can be added by using the method addDefaultCapacityProviderStrategy
. A capacity provider strategy cannot contain a mix of EC2 Autoscaling Group capacity providers and Fargate providers.
AsgCapacityProvider capacityProvider;
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 } });
AsgCapacityProvider capacityProvider;
var cluster = new Cluster(this, "EcsCluster", new ClusterProps {
EnableFargateCapacityProviders = true
});
cluster.AddAsgCapacityProvider(capacityProvider);
cluster.AddDefaultCapacityProviderStrategy(new [] { new 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.
IDictionary<string, string>[] inferenceAccelerators = new [] { new Dictionary<string, string> {
{ "deviceName", "device1" },
{ "deviceType", "eia2.medium" }
} };
var taskDefinition = new Ec2TaskDefinition(this, "Ec2TaskDef", new 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.
TaskDefinition taskDefinition;
var inferenceAcceleratorResources = new [] { "device1" };
taskDefinition.AddContainer("cont", new ContainerDefinitionOptions {
Image = ContainerImage.FromRegistry("test"),
MemoryLimitMiB = 1024,
InferenceAcceleratorResources = inferenceAcceleratorResources
});
ECS Exec command
Please note, ECS Exec leverages AWS Systems Manager (SSM). So as a prerequisite for the exec command to work, you need to have the SSM plugin for the AWS CLI installed locally. For more information, see Install Session Manager plugin for AWS CLI.
To enable the ECS Exec feature for your containers, set the boolean flag enableExecuteCommand
to true
in
your Ec2Service
or FargateService
.
Cluster cluster;
TaskDefinition taskDefinition;
var service = new Ec2Service(this, "Service", new Ec2ServiceProps {
Cluster = cluster,
TaskDefinition = taskDefinition,
EnableExecuteCommand = 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.
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
}
});
Amazon ECS Service Connect
Service Connect is a managed AWS mesh network offering. It simplifies DNS queries and inter-service communication for ECS Services by allowing customers to set up simple DNS aliases for their services, which are accessible to all services that have enabled Service Connect.
To enable Service Connect, you must have created a CloudMap namespace. The CDK can infer your cluster's default CloudMap namespace, or you can specify a custom namespace. You must also have created a named port mapping on at least one container in your Task Definition.
Cluster cluster;
TaskDefinition taskDefinition;
ContainerDefinitionOptions containerOptions;
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,
ServiceConnectConfiguration = new ServiceConnectProps {
Services = new [] { new ServiceConnectService {
PortMappingName = "api",
DnsName = "http-api",
Port = 80
} }
}
});
Service Connect-enabled services may now reach this service at http-api:80
. Traffic to this endpoint will
be routed to the container's port 8080.
To opt a service into using service connect without advertising a port, simply call the 'enableServiceConnect' method on an initialized service.
Cluster cluster;
TaskDefinition taskDefinition;
var service = new FargateService(this, "Service", new FargateServiceProps {
Cluster = cluster,
TaskDefinition = taskDefinition
});
service.EnableServiceConnect();
Service Connect also allows custom logging, Service Discovery name, and configuration of the port where service connect traffic is received.
Cluster cluster;
TaskDefinition taskDefinition;
var customService = new FargateService(this, "CustomizedService", new FargateServiceProps {
Cluster = cluster,
TaskDefinition = taskDefinition,
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"
} }
}
});
To set a timeout for service connect, use idleTimeout
and perRequestTimeout
.
Note: If idleTimeout
is set to a time that is less than perRequestTimeout
, the connection will close when
the idleTimeout
is reached and not the perRequestTimeout
.
Cluster cluster;
TaskDefinition taskDefinition;
var service = new FargateService(this, "Service", new FargateServiceProps {
Cluster = cluster,
TaskDefinition = taskDefinition,
ServiceConnectConfiguration = new ServiceConnectProps {
Services = new [] { new ServiceConnectService {
PortMappingName = "api",
IdleTimeout = Duration.Minutes(5),
PerRequestTimeout = Duration.Minutes(5)
} }
}
});
Visit <a href="https://aws.amazon.com/about-aws/whats-new/2024/01/amazon-ecs-configurable-timeout-service-connect/">Amazon ECS support for configurable timeout for services running with Service Connect</a> for more details.
ServiceManagedVolume
Amazon ECS now supports the attachment of Amazon Elastic Block Store (EBS) volumes to ECS tasks,
allowing you to utilize persistent, high-performance block storage with your ECS services.
This feature supports various use cases, such as using EBS volumes as extended ephemeral storage or
loading data from EBS snapshots.
You can also specify encrypted: true
so that ECS will manage the KMS key. If you want to use your own KMS key, you may do so by providing both encrypted: true
and kmsKeyId
.
You can only attach a single volume for each task in the ECS Service.
To add an empty EBS Volume to an ECS Service, call service.addVolume().
Cluster cluster;
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
});
service.AddVolume(volume);
To create an EBS volume from an existing snapshot by specifying the snapShotId
while adding a volume to the service.
ContainerDefinition container;
Cluster cluster;
TaskDefinition taskDefinition;
var volumeFromSnapshot = new ServiceManagedVolume(this, "EBSVolume", new ServiceManagedVolumeProps {
Name = "nginx-vol",
ManagedEBSVolume = new ServiceManagedEBSVolumeConfiguration {
SnapShotId = "snap-066877671789bd71b",
VolumeType = EbsDeviceVolumeType.GP3,
FileSystemType = FileSystemType.XFS
}
});
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
});
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
.
var taskDefinition = new Ec2TaskDefinition(this, "TaskDef");
taskDefinition.AddContainer("TheContainer", new ContainerDefinitionOptions {
Image = ContainerImage.FromRegistry("example-image"),
PseudoTerminal = true
});
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.
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
} }
});
Classes
AddAutoScalingGroupCapacityOptions | The properties for adding an AutoScalingGroup. |
AddCapacityOptions | The properties for adding instance capacity to an AutoScalingGroup. |
AlarmBehavior | Deployment behavior when an ECS Service Deployment Alarm is triggered. |
AmiHardwareType | The ECS-optimized AMI variant to use. |
AppMeshProxyConfiguration | The class for App Mesh proxy configurations. |
AppMeshProxyConfigurationConfigProps | The configuration to use when setting an App Mesh proxy configuration. |
AppMeshProxyConfigurationProps | Interface for setting the properties of proxy configuration. |
AppProtocol | Service connect app protocol. |
AsgCapacityProvider | An Auto Scaling Group Capacity Provider. |
AsgCapacityProviderProps | The options for creating an Auto Scaling Group Capacity Provider. |
AssetEnvironmentFile | Environment file from a local directory. |
AssetImage | An image that will be built from a local directory with a Dockerfile. |
AssetImageProps | The properties for building an AssetImage. |
AssociateCloudMapServiceOptions | The options for using a cloudmap service. |
AuthorizationConfig | The authorization configuration details for the Amazon EFS file system. |
AwsLogDriver | A log driver that sends log information to CloudWatch Logs. |
AwsLogDriverMode | awslogs provides two modes for delivering messages from the container to the log driver. |
AwsLogDriverProps | Specifies the awslogs log driver configuration options. |
BaseLogDriverProps | |
BaseMountPoint | The base details of where a volume will be mounted within a container. |
BaseService | The base class for Ec2Service and FargateService services. |
BaseServiceOptions | The properties for the base Ec2Service or FargateService service. |
BaseServiceProps | Complete base service properties that are required to be supplied by the implementation of the BaseService class. |
BinPackResource | Instance resource used for bin packing. |
BottlerocketEcsVariant | Amazon ECS variant. |
BottleRocketImage | Construct an Bottlerocket image from the latest AMI published in SSM. |
BottleRocketImageProps | Properties for BottleRocketImage. |
BuiltInAttributes | The built-in container instance attributes. |
Capability | A Linux capability. |
CapacityProviderStrategy | A Capacity Provider strategy to use for the service. |
CfnCapacityProvider | Creates a new capacity provider. |
CfnCapacityProvider.AutoScalingGroupProviderProperty | The details of the Auto Scaling group for the capacity provider. |
CfnCapacityProvider.ManagedScalingProperty | The managed scaling settings for the Auto Scaling group capacity provider. |
CfnCapacityProviderProps | Properties for defining a |
CfnCluster | The |
CfnCluster.CapacityProviderStrategyItemProperty | The |
CfnCluster.ClusterConfigurationProperty | The execute command and managed storage configuration for the cluster. |
CfnCluster.ClusterSettingsProperty | The settings to use when creating a cluster. |
CfnCluster.ExecuteCommandConfigurationProperty | The details of the execute command configuration. |
CfnCluster.ExecuteCommandLogConfigurationProperty | The log configuration for the results of the execute command actions. |
CfnCluster.ManagedStorageConfigurationProperty | The managed storage configuration for the cluster. |
CfnCluster.ServiceConnectDefaultsProperty | Use this parameter to set a default Service Connect namespace. |
CfnClusterCapacityProviderAssociations | The |
CfnClusterCapacityProviderAssociations.CapacityProviderStrategyProperty | The |
CfnClusterCapacityProviderAssociationsProps | Properties for defining a |
CfnClusterProps | Properties for defining a |
CfnPrimaryTaskSet | Modifies which task set in a service is the primary task set. |
CfnPrimaryTaskSetProps | Properties for defining a |
CfnService | The |
CfnService.AwsVpcConfigurationProperty | An object representing the networking details for a task or service. |
CfnService.CapacityProviderStrategyItemProperty | The details of a capacity provider strategy. |
CfnService.DeploymentAlarmsProperty | 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 | The deployment circuit breaker can only be used for services using the rolling update ( |
CfnService.DeploymentConfigurationProperty | Optional deployment parameters that control how many tasks run during a deployment and the ordering of stopping and starting tasks. |
CfnService.DeploymentControllerProperty | The deployment controller to use for the service. |
CfnService.EBSTagSpecificationProperty | The tag specifications of an Amazon EBS volume. |
CfnService.LoadBalancerProperty | The |
CfnService.LogConfigurationProperty | The log configuration for the container. |
CfnService.NetworkConfigurationProperty | The network configuration for a task or service. |
CfnService.PlacementConstraintProperty | An object representing a constraint on task placement. |
CfnService.PlacementStrategyProperty | The task placement strategy for a task or service. |
CfnService.SecretProperty | An object representing the secret to expose to your container. |
CfnService.ServiceConnectClientAliasProperty | Each alias ("endpoint") is a fully-qualified name and port number that other tasks ("clients") can use to connect to this service. |
CfnService.ServiceConnectConfigurationProperty | The Service Connect configuration of your Amazon ECS service. |
CfnService.ServiceConnectServiceProperty | The Service Connect service object configuration. |
CfnService.ServiceConnectTlsCertificateAuthorityProperty | The certificate root authority that secures your service. |
CfnService.ServiceConnectTlsConfigurationProperty | The key that encrypts and decrypts your resources for Service Connect TLS. |
CfnService.ServiceManagedEBSVolumeConfigurationProperty | The configuration for the Amazon EBS volume that Amazon ECS creates and manages on your behalf. |
CfnService.ServiceRegistryProperty | The details for the service registry. |
CfnService.ServiceVolumeConfigurationProperty | The configuration for a volume specified in the task definition as a volume that is configured at launch time. |
CfnService.TimeoutConfigurationProperty | An object that represents the timeout configurations for Service Connect. |
CfnServiceProps | Properties for defining a |
CfnTaskDefinition | Registers a new task definition from the supplied |
CfnTaskDefinition.AuthorizationConfigProperty | The authorization configuration details for the Amazon EFS file system. |
CfnTaskDefinition.ContainerDefinitionProperty | The |
CfnTaskDefinition.ContainerDependencyProperty | The |
CfnTaskDefinition.DeviceProperty | The |
CfnTaskDefinition.DockerVolumeConfigurationProperty | The |
CfnTaskDefinition.EFSVolumeConfigurationProperty | This parameter is specified when you're using an Amazon Elastic File System file system for task storage. |
CfnTaskDefinition.EnvironmentFileProperty | A list of files containing the environment variables to pass to a container. |
CfnTaskDefinition.EphemeralStorageProperty | The amount of ephemeral storage to allocate for the task. |
CfnTaskDefinition.FirelensConfigurationProperty | The FireLens configuration for the container. |
CfnTaskDefinition.FSxAuthorizationConfigProperty | The authorization configuration details for Amazon FSx for Windows File Server file system. |
CfnTaskDefinition.FSxWindowsFileServerVolumeConfigurationProperty | This parameter is specified when you're using Amazon FSx for Windows File Server file system for task storage. |
CfnTaskDefinition.HealthCheckProperty | The |
CfnTaskDefinition.HostEntryProperty | The |
CfnTaskDefinition.HostVolumePropertiesProperty | The |
CfnTaskDefinition.InferenceAcceleratorProperty | Details on an Elastic Inference accelerator. |
CfnTaskDefinition.KernelCapabilitiesProperty | The Linux capabilities to add or remove from the default Docker configuration for a container defined in the task definition. |
CfnTaskDefinition.KeyValuePairProperty | A key-value pair object. |
CfnTaskDefinition.LinuxParametersProperty | The Linux-specific options that are applied to the container, such as Linux KernelCapabilities . |
CfnTaskDefinition.LogConfigurationProperty | The |
CfnTaskDefinition.MountPointProperty | The details for a volume mount point that's used in a container definition. |
CfnTaskDefinition.PortMappingProperty | The |
CfnTaskDefinition.ProxyConfigurationProperty | The configuration details for the App Mesh proxy. |
CfnTaskDefinition.RepositoryCredentialsProperty | The repository credentials for private registry authentication. |
CfnTaskDefinition.ResourceRequirementProperty | The type and amount of a resource to assign to a container. |
CfnTaskDefinition.RestartPolicyProperty | 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 | Information about the platform for the Amazon ECS service or task. |
CfnTaskDefinition.SecretProperty | An object representing the secret to expose to your container. |
CfnTaskDefinition.SystemControlProperty | A list of namespaced kernel parameters to set in the container. |
CfnTaskDefinition.TaskDefinitionPlacementConstraintProperty | The constraint on task placement in the task definition. |
CfnTaskDefinition.TmpfsProperty | The container path, mount options, and size of the tmpfs mount. |
CfnTaskDefinition.UlimitProperty | The |
CfnTaskDefinition.VolumeFromProperty | Details on a data volume from another container in the same task definition. |
CfnTaskDefinition.VolumeProperty | The data volume configuration for tasks launched using this task definition. |
CfnTaskDefinitionProps | Properties for defining a |
CfnTaskSet | Create a task set in the specified cluster and service. |
CfnTaskSet.AwsVpcConfigurationProperty | An object representing the networking details for a task or service. |
CfnTaskSet.LoadBalancerProperty | The load balancer configuration to use with a service or task set. |
CfnTaskSet.NetworkConfigurationProperty | The network configuration for a task or service. |
CfnTaskSet.ScaleProperty | A floating-point percentage of the desired number of tasks to place and keep running in the task set. |
CfnTaskSet.ServiceRegistryProperty | The details for the service registry. |
CfnTaskSetProps | Properties for defining a |
CloudMapNamespaceOptions | The options for creating an AWS Cloud Map namespace. |
CloudMapOptions | The options to enabling AWS Cloud Map for an Amazon ECS service. |
Cluster | A regional grouping of one or more container instances on which you can run tasks and services. |
ClusterAttributes | The properties to import from the ECS cluster. |
ClusterProps | The properties used to define an ECS cluster. |
CommonTaskDefinitionAttributes | The common task definition attributes used across all types of task definitions. |
CommonTaskDefinitionProps | The common properties for all task definitions. |
Compatibility | The task launch type compatibility requirement. |
ContainerDefinition | A container definition is used in a task definition to describe the containers that are launched as part of a task. |
ContainerDefinitionOptions | |
ContainerDefinitionProps | The properties in a container definition. |
ContainerDependency | The details of a dependency on another container in the task definition. |
ContainerDependencyCondition | |
ContainerImage | Constructs for types of container images. |
ContainerImageConfig | The configuration for creating a container image. |
ContainerMountPoint | Defines the mount point details for attaching a volume to a container. |
CpuArchitecture | The CpuArchitecture for Fargate Runtime Platform. |
CpuUtilizationScalingProps | The properties for enabling scaling based on CPU utilization. |
CredentialSpec | Base construct for a credential specification (CredSpec). |
CredentialSpecConfig | Configuration for a credential specification (CredSpec) used for a ECS container. |
DeploymentAlarmConfig | Configuration for deployment alarms. |
DeploymentAlarmOptions | Options for deployment alarms. |
DeploymentCircuitBreaker | The deployment circuit breaker to use for the service. |
DeploymentController | The deployment controller to use for the service. |
DeploymentControllerType | The deployment controller type to use for the service. |
Device | A container instance host device. |
DevicePermission | Permissions for device access. |
DockerVolumeConfiguration | The configuration for a Docker volume. |
DomainJoinedCredentialSpec | Credential specification (CredSpec) file. |
DomainlessCredentialSpec | Credential specification for domainless gMSA. |
EbsPropagatedTagSource | Propagate tags for EBS Volume Configuration from either service or task definition. |
EBSTagSpecification | Tag Specification for EBS volume. |
Ec2Service | This creates a service using the EC2 launch type on an ECS cluster. |
Ec2ServiceAttributes | The properties to import from the service using the EC2 launch type. |
Ec2ServiceProps | The properties for defining a service using the EC2 launch type. |
Ec2TaskDefinition | The details of a task definition run on an EC2 cluster. |
Ec2TaskDefinitionAttributes | Attributes used to import an existing EC2 task definition. |
Ec2TaskDefinitionProps | The properties for a task definition run on an EC2 cluster. |
EcrImage | An image from an Amazon ECR repository. |
EcsOptimizedImage | Construct a Linux or Windows machine image from the latest ECS Optimized AMI published in SSM. |
EcsOptimizedImageOptions | Additional configuration properties for EcsOptimizedImage factory functions. |
EcsTarget | |
EfsVolumeConfiguration | The configuration for an Elastic FileSystem volume. |
EnvironmentFile | Constructs for types of environment files. |
EnvironmentFileConfig | Configuration for the environment file. |
EnvironmentFileType | Type of environment file to be included in the container definition. |
ExecuteCommandConfiguration | The details of the execute command configuration. |
ExecuteCommandLogConfiguration | The log configuration for the results of the execute command actions. |
ExecuteCommandLogging | The log settings to use to for logging the execute command session. |
ExternalService | This creates a service using the External launch type on an ECS cluster. |
ExternalServiceAttributes | The properties to import from the service using the External launch type. |
ExternalServiceProps | The properties for defining a service using the External launch type. |
ExternalTaskDefinition | The details of a task definition run on an External cluster. |
ExternalTaskDefinitionAttributes | Attributes used to import an existing External task definition. |
ExternalTaskDefinitionProps | The properties for a task definition run on an External cluster. |
FargatePlatformVersion | The platform version on which to run your service. |
FargateService | This creates a service using the Fargate launch type on an ECS cluster. |
FargateServiceAttributes | The properties to import from the service using the Fargate launch type. |
FargateServiceProps | The properties for defining a service using the Fargate launch type. |
FargateTaskDefinition | The details of a task definition run on a Fargate cluster. |
FargateTaskDefinitionAttributes | Attributes used to import an existing Fargate task definition. |
FargateTaskDefinitionProps | The properties for a task definition. |
FileSystemType | FileSystemType for Service Managed EBS Volume Configuration. |
FirelensConfig | Firelens Configuration https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_firelens.html#firelens-taskdef. |
FirelensConfigFileType | Firelens configuration file type, s3 or file path. |
FireLensLogDriver | 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 | Specifies the firelens log driver configuration options. |
FirelensLogRouter | Firelens log router. |
FirelensLogRouterDefinitionOptions | The options for creating a firelens log router. |
FirelensLogRouterProps | The properties in a firelens log router. |
FirelensLogRouterType | Firelens log router type, fluentbit or fluentd. |
FirelensOptions | The options for firelens log router https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_firelens.html#firelens-taskdef-customconfig. |
FluentdLogDriver | A log driver that sends log information to journald Logs. |
FluentdLogDriverProps | Specifies the fluentd log driver configuration options. |
GelfCompressionType | The type of compression the GELF driver uses to compress each log message. |
GelfLogDriver | A log driver that sends log information to journald Logs. |
GelfLogDriverProps | Specifies the journald log driver configuration options. |
GenericLogDriver | A log driver that sends logs to the specified driver. |
GenericLogDriverProps | The configuration to use when creating a log driver. |
HealthCheck | The health check command and associated configuration parameters for the container. |
Host | The details on a container instance bind mount host volume. |
InferenceAccelerator | Elastic Inference Accelerator. |
IpcMode | The IPC resource namespace to use for the containers in the task. |
JournaldLogDriver | A log driver that sends log information to journald Logs. |
JournaldLogDriverProps | Specifies the journald log driver configuration options. |
JsonFileLogDriver | A log driver that sends log information to json-file Logs. |
JsonFileLogDriverProps | Specifies the json-file log driver configuration options. |
LaunchType | The launch type of an ECS service. |
LinuxParameters | Linux-specific options that are applied to the container. |
LinuxParametersProps | The properties for defining Linux-specific options that are applied to the container. |
ListenerConfig | Base class for configuring listener when registering targets. |
LoadBalancerTargetOptions | Properties for defining an ECS target. |
LogDriver | The base class for log drivers. |
LogDriverConfig | The configuration to use when creating a log driver. |
LogDrivers | The base class for log drivers. |
MachineImageType | The machine image type. |
MemoryUtilizationScalingProps | The properties for enabling scaling based on memory utilization. |
MountPoint | The details of data volume mount points for a container. |
NetworkMode | The networking mode to use for the containers in the task. |
OperatingSystemFamily | The operating system for Fargate Runtime Platform. |
PidMode | The process namespace to use for the containers in the task. |
PlacementConstraint | The placement constraints to use for tasks in the service. For more information, see Amazon ECS Task Placement Constraints. |
PlacementStrategy | The placement strategies to use for tasks in the service. For more information, see Amazon ECS Task Placement Strategies. |
PortMap | PortMap ValueObjectClass having by ContainerDefinition. |
PortMapping | Port mappings allow containers to access ports on the host container instance to send or receive traffic. |
PropagatedTagSource | Propagate tags from either service or task definition. |
Protocol | Network protocol. |
ProxyConfiguration | The base class for proxy configurations. |
ProxyConfigurations | The base class for proxy configurations. |
RepositoryImage | An image hosted in a public or private repository. |
RepositoryImageProps | The properties for an image hosted in a public or private repository. |
RequestCountScalingProps | The properties for enabling scaling based on Application Load Balancer (ALB) request counts. |
RuntimePlatform | The interface for Runtime Platform. |
S3EnvironmentFile | Environment file from S3. |
ScalableTaskCount | The scalable attribute representing task count. |
ScalableTaskCountProps | The properties of a scalable attribute representing task count. |
Scope | The scope for the Docker volume that determines its lifecycle. |
ScratchSpace | The temporary disk space mounted to the container. |
Secret | A secret environment variable. |
SecretVersionInfo | Specify the secret's version id or version stage. |
ServiceConnect | ServiceConnect ValueObjectClass having by ContainerDefinition. |
ServiceConnectProps | Interface for Service Connect configuration. |
ServiceConnectService | Interface for service connect Service props. |
ServiceManagedEBSVolumeConfiguration | Represents the configuration for an ECS Service managed EBS volume. |
ServiceManagedVolume | Represents a service-managed volume and always configured at launch. |
ServiceManagedVolumeProps | Represents the Volume configuration for an ECS service. |
SplunkLogDriver | A log driver that sends log information to splunk Logs. |
SplunkLogDriverProps | Specifies the splunk log driver configuration options. |
SplunkLogFormat | Log Message Format. |
SyslogLogDriver | A log driver that sends log information to syslog Logs. |
SyslogLogDriverProps | Specifies the syslog log driver configuration options. |
SystemControl | Kernel parameters to set in the container. |
TagParameterContainerImage | A special type of |
TaskDefinition | The base class for all task definitions. |
TaskDefinitionAttributes | A reference to an existing task definition. |
TaskDefinitionProps | The properties for task definitions. |
TaskDefinitionRevision | Represents revision of a task definition, either a specific numbered revision or the |
Tmpfs | The details of a tmpfs mount for a container. |
TmpfsMountOption | The supported options for a tmpfs mount for a container. |
TrackCustomMetricProps | The properties for enabling target tracking scaling based on a custom CloudWatch metric. |
Ulimit | The ulimit settings to pass to the container. |
UlimitName | Type of resource to set a limit on. |
Volume | A data volume used in a task definition. |
VolumeFrom | The details on a data volume from another container in the same task definition. |
WindowsOptimizedVersion | ECS-optimized Windows version list. |
Interfaces
CfnCapacityProvider.IAutoScalingGroupProviderProperty | The details of the Auto Scaling group for the capacity provider. |
CfnCapacityProvider.IManagedScalingProperty | The managed scaling settings for the Auto Scaling group capacity provider. |
CfnCluster.ICapacityProviderStrategyItemProperty | The |
CfnCluster.IClusterConfigurationProperty | The execute command and managed storage configuration for the cluster. |
CfnCluster.IClusterSettingsProperty | The settings to use when creating a cluster. |
CfnCluster.IExecuteCommandConfigurationProperty | The details of the execute command configuration. |
CfnCluster.IExecuteCommandLogConfigurationProperty | The log configuration for the results of the execute command actions. |
CfnCluster.IManagedStorageConfigurationProperty | The managed storage configuration for the cluster. |
CfnCluster.IServiceConnectDefaultsProperty | Use this parameter to set a default Service Connect namespace. |
CfnClusterCapacityProviderAssociations.ICapacityProviderStrategyProperty | The |
CfnService.IAwsVpcConfigurationProperty | An object representing the networking details for a task or service. |
CfnService.ICapacityProviderStrategyItemProperty | The details of a capacity provider strategy. |
CfnService.IDeploymentAlarmsProperty | 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.IDeploymentCircuitBreakerProperty | The deployment circuit breaker can only be used for services using the rolling update ( |
CfnService.IDeploymentConfigurationProperty | Optional deployment parameters that control how many tasks run during a deployment and the ordering of stopping and starting tasks. |
CfnService.IDeploymentControllerProperty | The deployment controller to use for the service. |
CfnService.IEBSTagSpecificationProperty | The tag specifications of an Amazon EBS volume. |
CfnService.ILoadBalancerProperty | The |
CfnService.ILogConfigurationProperty | The log configuration for the container. |
CfnService.INetworkConfigurationProperty | The network configuration for a task or service. |
CfnService.IPlacementConstraintProperty | An object representing a constraint on task placement. |
CfnService.IPlacementStrategyProperty | The task placement strategy for a task or service. |
CfnService.ISecretProperty | An object representing the secret to expose to your container. |
CfnService.IServiceConnectClientAliasProperty | Each alias ("endpoint") is a fully-qualified name and port number that other tasks ("clients") can use to connect to this service. |
CfnService.IServiceConnectConfigurationProperty | The Service Connect configuration of your Amazon ECS service. |
CfnService.IServiceConnectServiceProperty | The Service Connect service object configuration. |
CfnService.IServiceConnectTlsCertificateAuthorityProperty | The certificate root authority that secures your service. |
CfnService.IServiceConnectTlsConfigurationProperty | The key that encrypts and decrypts your resources for Service Connect TLS. |
CfnService.IServiceManagedEBSVolumeConfigurationProperty | The configuration for the Amazon EBS volume that Amazon ECS creates and manages on your behalf. |
CfnService.IServiceRegistryProperty | The details for the service registry. |
CfnService.IServiceVolumeConfigurationProperty | The configuration for a volume specified in the task definition as a volume that is configured at launch time. |
CfnService.ITimeoutConfigurationProperty | An object that represents the timeout configurations for Service Connect. |
CfnTaskDefinition.IAuthorizationConfigProperty | The authorization configuration details for the Amazon EFS file system. |
CfnTaskDefinition.IContainerDefinitionProperty | The |
CfnTaskDefinition.IContainerDependencyProperty | The |
CfnTaskDefinition.IDeviceProperty | The |
CfnTaskDefinition.IDockerVolumeConfigurationProperty | The |
CfnTaskDefinition.IEFSVolumeConfigurationProperty | This parameter is specified when you're using an Amazon Elastic File System file system for task storage. |
CfnTaskDefinition.IEnvironmentFileProperty | A list of files containing the environment variables to pass to a container. |
CfnTaskDefinition.IEphemeralStorageProperty | The amount of ephemeral storage to allocate for the task. |
CfnTaskDefinition.IFirelensConfigurationProperty | The FireLens configuration for the container. |
CfnTaskDefinition.IFSxAuthorizationConfigProperty | The authorization configuration details for Amazon FSx for Windows File Server file system. |
CfnTaskDefinition.IFSxWindowsFileServerVolumeConfigurationProperty | This parameter is specified when you're using Amazon FSx for Windows File Server file system for task storage. |
CfnTaskDefinition.IHealthCheckProperty | The |
CfnTaskDefinition.IHostEntryProperty | The |
CfnTaskDefinition.IHostVolumePropertiesProperty | The |
CfnTaskDefinition.IInferenceAcceleratorProperty | Details on an Elastic Inference accelerator. |
CfnTaskDefinition.IKernelCapabilitiesProperty | The Linux capabilities to add or remove from the default Docker configuration for a container defined in the task definition. |
CfnTaskDefinition.IKeyValuePairProperty | A key-value pair object. |
CfnTaskDefinition.ILinuxParametersProperty | The Linux-specific options that are applied to the container, such as Linux KernelCapabilities . |
CfnTaskDefinition.ILogConfigurationProperty | The |
CfnTaskDefinition.IMountPointProperty | The details for a volume mount point that's used in a container definition. |
CfnTaskDefinition.IPortMappingProperty | The |
CfnTaskDefinition.IProxyConfigurationProperty | The configuration details for the App Mesh proxy. |
CfnTaskDefinition.IRepositoryCredentialsProperty | The repository credentials for private registry authentication. |
CfnTaskDefinition.IResourceRequirementProperty | The type and amount of a resource to assign to a container. |
CfnTaskDefinition.IRestartPolicyProperty | You can enable a restart policy for each container defined in your task definition, to overcome transient failures faster and maintain task availability. |
CfnTaskDefinition.IRuntimePlatformProperty | Information about the platform for the Amazon ECS service or task. |
CfnTaskDefinition.ISecretProperty | An object representing the secret to expose to your container. |
CfnTaskDefinition.ISystemControlProperty | A list of namespaced kernel parameters to set in the container. |
CfnTaskDefinition.ITaskDefinitionPlacementConstraintProperty | The constraint on task placement in the task definition. |
CfnTaskDefinition.ITmpfsProperty | The container path, mount options, and size of the tmpfs mount. |
CfnTaskDefinition.IUlimitProperty | The |
CfnTaskDefinition.IVolumeFromProperty | Details on a data volume from another container in the same task definition. |
CfnTaskDefinition.IVolumeProperty | The data volume configuration for tasks launched using this task definition. |
CfnTaskSet.IAwsVpcConfigurationProperty | An object representing the networking details for a task or service. |
CfnTaskSet.ILoadBalancerProperty | The load balancer configuration to use with a service or task set. |
CfnTaskSet.INetworkConfigurationProperty | The network configuration for a task or service. |
CfnTaskSet.IScaleProperty | A floating-point percentage of the desired number of tasks to place and keep running in the task set. |
CfnTaskSet.IServiceRegistryProperty | The details for the service registry. |
IAddAutoScalingGroupCapacityOptions | The properties for adding an AutoScalingGroup. |
IAddCapacityOptions | The properties for adding instance capacity to an AutoScalingGroup. |
IAppMeshProxyConfigurationConfigProps | The configuration to use when setting an App Mesh proxy configuration. |
IAppMeshProxyConfigurationProps | Interface for setting the properties of proxy configuration. |
IAsgCapacityProviderProps | The options for creating an Auto Scaling Group Capacity Provider. |
IAssetImageProps | The properties for building an AssetImage. |
IAssociateCloudMapServiceOptions | The options for using a cloudmap service. |
IAuthorizationConfig | The authorization configuration details for the Amazon EFS file system. |
IAwsLogDriverProps | Specifies the awslogs log driver configuration options. |
IBaseLogDriverProps | |
IBaseMountPoint | The base details of where a volume will be mounted within a container. |
IBaseService | The interface for BaseService. |
IBaseServiceOptions | The properties for the base Ec2Service or FargateService service. |
IBaseServiceProps | Complete base service properties that are required to be supplied by the implementation of the BaseService class. |
IBottleRocketImageProps | Properties for BottleRocketImage. |
ICapacityProviderStrategy | A Capacity Provider strategy to use for the service. |
ICfnCapacityProviderProps | Properties for defining a |
ICfnClusterCapacityProviderAssociationsProps | Properties for defining a |
ICfnClusterProps | Properties for defining a |
ICfnPrimaryTaskSetProps | Properties for defining a |
ICfnServiceProps | Properties for defining a |
ICfnTaskDefinitionProps | Properties for defining a |
ICfnTaskSetProps | Properties for defining a |
ICloudMapNamespaceOptions | The options for creating an AWS Cloud Map namespace. |
ICloudMapOptions | The options to enabling AWS Cloud Map for an Amazon ECS service. |
ICluster | A regional grouping of one or more container instances on which you can run tasks and services. |
IClusterAttributes | The properties to import from the ECS cluster. |
IClusterProps | The properties used to define an ECS cluster. |
ICommonTaskDefinitionAttributes | The common task definition attributes used across all types of task definitions. |
ICommonTaskDefinitionProps | The common properties for all task definitions. |
IContainerDefinitionOptions | |
IContainerDefinitionProps | The properties in a container definition. |
IContainerDependency | The details of a dependency on another container in the task definition. |
IContainerImageConfig | The configuration for creating a container image. |
IContainerMountPoint | Defines the mount point details for attaching a volume to a container. |
ICpuUtilizationScalingProps | The properties for enabling scaling based on CPU utilization. |
ICredentialSpecConfig | Configuration for a credential specification (CredSpec) used for a ECS container. |
IDeploymentAlarmConfig | Configuration for deployment alarms. |
IDeploymentAlarmOptions | Options for deployment alarms. |
IDeploymentCircuitBreaker | The deployment circuit breaker to use for the service. |
IDeploymentController | The deployment controller to use for the service. |
IDevice | A container instance host device. |
IDockerVolumeConfiguration | The configuration for a Docker volume. |
IEBSTagSpecification | Tag Specification for EBS volume. |
IEc2Service | The interface for a service using the EC2 launch type on an ECS cluster. |
IEc2ServiceAttributes | The properties to import from the service using the EC2 launch type. |
IEc2ServiceProps | The properties for defining a service using the EC2 launch type. |
IEc2TaskDefinition | The interface of a task definition run on an EC2 cluster. |
IEc2TaskDefinitionAttributes | Attributes used to import an existing EC2 task definition. |
IEc2TaskDefinitionProps | The properties for a task definition run on an EC2 cluster. |
IEcsLoadBalancerTarget | Interface for ECS load balancer target. |
IEcsOptimizedImageOptions | Additional configuration properties for EcsOptimizedImage factory functions. |
IEcsTarget | |
IEfsVolumeConfiguration | The configuration for an Elastic FileSystem volume. |
IEnvironmentFileConfig | Configuration for the environment file. |
IExecuteCommandConfiguration | The details of the execute command configuration. |
IExecuteCommandLogConfiguration | The log configuration for the results of the execute command actions. |
IExternalService | The interface for a service using the External launch type on an ECS cluster. |
IExternalServiceAttributes | The properties to import from the service using the External launch type. |
IExternalServiceProps | The properties for defining a service using the External launch type. |
IExternalTaskDefinition | The interface of a task definition run on an External cluster. |
IExternalTaskDefinitionAttributes | Attributes used to import an existing External task definition. |
IExternalTaskDefinitionProps | The properties for a task definition run on an External cluster. |
IFargateService | The interface for a service using the Fargate launch type on an ECS cluster. |
IFargateServiceAttributes | The properties to import from the service using the Fargate launch type. |
IFargateServiceProps | The properties for defining a service using the Fargate launch type. |
IFargateTaskDefinition | The interface of a task definition run on a Fargate cluster. |
IFargateTaskDefinitionAttributes | Attributes used to import an existing Fargate task definition. |
IFargateTaskDefinitionProps | The properties for a task definition. |
IFirelensConfig | Firelens Configuration https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_firelens.html#firelens-taskdef. |
IFireLensLogDriverProps | Specifies the firelens log driver configuration options. |
IFirelensLogRouterDefinitionOptions | The options for creating a firelens log router. |
IFirelensLogRouterProps | The properties in a firelens log router. |
IFirelensOptions | The options for firelens log router https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using_firelens.html#firelens-taskdef-customconfig. |
IFluentdLogDriverProps | Specifies the fluentd log driver configuration options. |
IGelfLogDriverProps | Specifies the journald log driver configuration options. |
IGenericLogDriverProps | The configuration to use when creating a log driver. |
IHealthCheck | The health check command and associated configuration parameters for the container. |
IHost | The details on a container instance bind mount host volume. |
IInferenceAccelerator | Elastic Inference Accelerator. |
IJournaldLogDriverProps | Specifies the journald log driver configuration options. |
IJsonFileLogDriverProps | Specifies the json-file log driver configuration options. |
ILinuxParametersProps | The properties for defining Linux-specific options that are applied to the container. |
ILoadBalancerTargetOptions | Properties for defining an ECS target. |
ILogDriverConfig | The configuration to use when creating a log driver. |
IMemoryUtilizationScalingProps | The properties for enabling scaling based on memory utilization. |
IMountPoint | The details of data volume mount points for a container. |
IPortMapping | Port mappings allow containers to access ports on the host container instance to send or receive traffic. |
IRepositoryImageProps | The properties for an image hosted in a public or private repository. |
IRequestCountScalingProps | The properties for enabling scaling based on Application Load Balancer (ALB) request counts. |
IRuntimePlatform | The interface for Runtime Platform. |
IScalableTaskCountProps | The properties of a scalable attribute representing task count. |
IScratchSpace | The temporary disk space mounted to the container. |
ISecretVersionInfo | Specify the secret's version id or version stage. |
IService | The interface for a service. |
IServiceConnectProps | Interface for Service Connect configuration. |
IServiceConnectService | Interface for service connect Service props. |
IServiceManagedEBSVolumeConfiguration | Represents the configuration for an ECS Service managed EBS volume. |
IServiceManagedVolumeProps | Represents the Volume configuration for an ECS service. |
ISplunkLogDriverProps | Specifies the splunk log driver configuration options. |
ISyslogLogDriverProps | Specifies the syslog log driver configuration options. |
ISystemControl | Kernel parameters to set in the container. |
ITaskDefinition | The interface for all task definitions. |
ITaskDefinitionAttributes | A reference to an existing task definition. |
ITaskDefinitionExtension | An extension for Task Definitions. |
ITaskDefinitionProps | The properties for task definitions. |
ITmpfs | The details of a tmpfs mount for a container. |
ITrackCustomMetricProps | The properties for enabling target tracking scaling based on a custom CloudWatch metric. |
IUlimit | The ulimit settings to pass to the container. |
IVolume | A data volume used in a task definition. |
IVolumeFrom | The details on a data volume from another container in the same task definition. |