Namespace Amazon.CDK.AWS.ECS.Patterns
CDK Construct library for higher-level ECS Constructs
This library provides higher-level Amazon ECS constructs which follow common architectural patterns. It contains:
Application Load Balanced Services
To define an Amazon ECS service that is behind an application load balancer, instantiate one of the following:
Cluster cluster;
var loadBalancedEcsService = new ApplicationLoadBalancedEc2Service(this, "Service", new ApplicationLoadBalancedEc2ServiceProps {
Cluster = cluster,
MemoryLimitMiB = 1024,
TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {
Image = ContainerImage.FromRegistry("test"),
Environment = new Dictionary<string, string> {
{ "TEST_ENVIRONMENT_VARIABLE1", "test environment variable 1 value" },
{ "TEST_ENVIRONMENT_VARIABLE2", "test environment variable 2 value" }
},
Command = new [] { "command" },
EntryPoint = new [] { "entry", "point" }
},
DesiredCount = 2
});
Cluster cluster;
var loadBalancedFargateService = new ApplicationLoadBalancedFargateService(this, "Service", new ApplicationLoadBalancedFargateServiceProps {
Cluster = cluster,
MemoryLimitMiB = 1024,
Cpu = 512,
TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
Command = new [] { "command" },
EntryPoint = new [] { "entry", "point" }
}
});
loadBalancedFargateService.TargetGroup.ConfigureHealthCheck(new HealthCheck {
Path = "/custom-health-path"
});
Instead of providing a cluster you can specify a VPC and CDK will create a new ECS cluster. If you deploy multiple services CDK will only create one cluster per VPC.
You can omit cluster
and vpc
to let CDK create a new VPC with two AZs and create a cluster inside this VPC.
You can customize the health check for your target group; otherwise it defaults to HTTP
over port 80
hitting path /
.
You can customize the health check configuration of the container via the healthCheck
property; otherwise it defaults to the health check configuration from the container.
Fargate services will use the LATEST
platform version by default, but you can override by providing a value for the platformVersion
property in the constructor.
Fargate services use the default VPC Security Group unless one or more are provided using the securityGroups
property in the constructor.
By setting redirectHTTP
to true, CDK will automatically create a listener on port 80 that redirects HTTP traffic to the HTTPS port.
If you specify the option recordType
you can decide if you want the construct to use CNAME or Route53-Aliases as record sets.
If you need to encrypt the traffic between the load balancer and the ECS tasks, you can set the targetProtocol
to HTTPS
.
Additionally, if more than one application target group are needed, instantiate one of the following:
// One application load balancer with one listener and two target groups.
Cluster cluster;
var loadBalancedEc2Service = new ApplicationMultipleTargetGroupsEc2Service(this, "Service", new ApplicationMultipleTargetGroupsEc2ServiceProps {
Cluster = cluster,
MemoryLimitMiB = 256,
TaskImageOptions = new ApplicationLoadBalancedTaskImageProps {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
},
TargetGroups = new [] { new ApplicationTargetProps {
ContainerPort = 80
}, new ApplicationTargetProps {
ContainerPort = 90,
PathPattern = "a/b/c",
Priority = 10
} }
});
// One application load balancer with one listener and two target groups.
Cluster cluster;
var loadBalancedFargateService = new ApplicationMultipleTargetGroupsFargateService(this, "Service", new ApplicationMultipleTargetGroupsFargateServiceProps {
Cluster = cluster,
MemoryLimitMiB = 1024,
Cpu = 512,
TaskImageOptions = new ApplicationLoadBalancedTaskImageProps {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
},
TargetGroups = new [] { new ApplicationTargetProps {
ContainerPort = 80
}, new ApplicationTargetProps {
ContainerPort = 90,
PathPattern = "a/b/c",
Priority = 10
} }
});
Network Load Balanced Services
To define an Amazon ECS service that is behind a network load balancer, instantiate one of the following:
Cluster cluster;
var loadBalancedEcsService = new NetworkLoadBalancedEc2Service(this, "Service", new NetworkLoadBalancedEc2ServiceProps {
Cluster = cluster,
MemoryLimitMiB = 1024,
TaskImageOptions = new NetworkLoadBalancedTaskImageOptions {
Image = ContainerImage.FromRegistry("test"),
Environment = new Dictionary<string, string> {
{ "TEST_ENVIRONMENT_VARIABLE1", "test environment variable 1 value" },
{ "TEST_ENVIRONMENT_VARIABLE2", "test environment variable 2 value" }
}
},
DesiredCount = 2
});
Cluster cluster;
var loadBalancedFargateService = new NetworkLoadBalancedFargateService(this, "Service", new NetworkLoadBalancedFargateServiceProps {
Cluster = cluster,
MemoryLimitMiB = 1024,
Cpu = 512,
TaskImageOptions = new NetworkLoadBalancedTaskImageOptions {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
}
});
The CDK will create a new Amazon ECS cluster if you specify a VPC and omit cluster
. If you deploy multiple services the CDK will only create one cluster per VPC.
If cluster
and vpc
are omitted, the CDK creates a new VPC with subnets in two Availability Zones and a cluster within this VPC.
If you specify the option recordType
you can decide if you want the construct to use CNAME or Route53-Aliases as record sets.
Additionally, if more than one network target group is needed, instantiate one of the following:
// Two network load balancers, each with their own listener and target group.
Cluster cluster;
var loadBalancedEc2Service = new NetworkMultipleTargetGroupsEc2Service(this, "Service", new NetworkMultipleTargetGroupsEc2ServiceProps {
Cluster = cluster,
MemoryLimitMiB = 256,
TaskImageOptions = new NetworkLoadBalancedTaskImageProps {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
},
LoadBalancers = new [] { new NetworkLoadBalancerProps {
Name = "lb1",
Listeners = new [] { new NetworkListenerProps {
Name = "listener1"
} }
}, new NetworkLoadBalancerProps {
Name = "lb2",
Listeners = new [] { new NetworkListenerProps {
Name = "listener2"
} }
} },
TargetGroups = new [] { new NetworkTargetProps {
ContainerPort = 80,
Listener = "listener1"
}, new NetworkTargetProps {
ContainerPort = 90,
Listener = "listener2"
} }
});
// Two network load balancers, each with their own listener and target group.
Cluster cluster;
var loadBalancedFargateService = new NetworkMultipleTargetGroupsFargateService(this, "Service", new NetworkMultipleTargetGroupsFargateServiceProps {
Cluster = cluster,
MemoryLimitMiB = 512,
TaskImageOptions = new NetworkLoadBalancedTaskImageProps {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
},
LoadBalancers = new [] { new NetworkLoadBalancerProps {
Name = "lb1",
Listeners = new [] { new NetworkListenerProps {
Name = "listener1"
} }
}, new NetworkLoadBalancerProps {
Name = "lb2",
Listeners = new [] { new NetworkListenerProps {
Name = "listener2"
} }
} },
TargetGroups = new [] { new NetworkTargetProps {
ContainerPort = 80,
Listener = "listener1"
}, new NetworkTargetProps {
ContainerPort = 90,
Listener = "listener2"
} }
});
Queue Processing Services
To define a service that creates a queue and reads from that queue, instantiate one of the following:
Cluster cluster;
var queueProcessingEc2Service = new QueueProcessingEc2Service(this, "Service", new QueueProcessingEc2ServiceProps {
Cluster = cluster,
MemoryLimitMiB = 1024,
Image = ContainerImage.FromRegistry("test"),
Command = new [] { "-c", "4", "amazon.com" },
EnableLogging = false,
DesiredTaskCount = 2,
Environment = new Dictionary<string, string> {
{ "TEST_ENVIRONMENT_VARIABLE1", "test environment variable 1 value" },
{ "TEST_ENVIRONMENT_VARIABLE2", "test environment variable 2 value" }
},
MaxScalingCapacity = 5,
ContainerName = "test"
});
Cluster cluster;
var queueProcessingFargateService = new QueueProcessingFargateService(this, "Service", new QueueProcessingFargateServiceProps {
Cluster = cluster,
MemoryLimitMiB = 512,
Image = ContainerImage.FromRegistry("test"),
Command = new [] { "-c", "4", "amazon.com" },
EnableLogging = false,
DesiredTaskCount = 2,
Environment = new Dictionary<string, string> {
{ "TEST_ENVIRONMENT_VARIABLE1", "test environment variable 1 value" },
{ "TEST_ENVIRONMENT_VARIABLE2", "test environment variable 2 value" }
},
MaxScalingCapacity = 5,
ContainerName = "test"
});
when queue not provided by user, CDK will create a primary queue and a dead letter queue with default redrive policy and attach permission to the task to be able to access the primary queue.
NOTE: QueueProcessingFargateService
adds a CPU Based scaling strategy by default. You can turn this off by setting disableCpuBasedScaling: true
.
Cluster cluster;
var queueProcessingFargateService = new QueueProcessingFargateService(this, "Service", new QueueProcessingFargateServiceProps {
Cluster = cluster,
MemoryLimitMiB = 512,
Image = ContainerImage.FromRegistry("test"),
Command = new [] { "-c", "4", "amazon.com" },
EnableLogging = false,
DesiredTaskCount = 2,
Environment = new Dictionary<string, string> {
{ "TEST_ENVIRONMENT_VARIABLE1", "test environment variable 1 value" },
{ "TEST_ENVIRONMENT_VARIABLE2", "test environment variable 2 value" }
},
MaxScalingCapacity = 5,
ContainerName = "test",
DisableCpuBasedScaling = true
});
To specify a custom target CPU utilization percentage for the scaling strategy use the cpuTargetUtilizationPercent
property:
Cluster cluster;
var queueProcessingFargateService = new QueueProcessingFargateService(this, "Service", new QueueProcessingFargateServiceProps {
Cluster = cluster,
MemoryLimitMiB = 512,
Image = ContainerImage.FromRegistry("test"),
Command = new [] { "-c", "4", "amazon.com" },
EnableLogging = false,
DesiredTaskCount = 2,
Environment = new Dictionary<string, object> { },
MaxScalingCapacity = 5,
ContainerName = "test",
CpuTargetUtilizationPercent = 90
});
Scheduled Tasks
To define a task that runs periodically, there are 2 options:
// Instantiate an Amazon EC2 Task to run at a scheduled interval
Cluster cluster;
var ecsScheduledTask = new ScheduledEc2Task(this, "ScheduledTask", new ScheduledEc2TaskProps {
Cluster = cluster,
ScheduledEc2TaskImageOptions = new ScheduledEc2TaskImageOptions {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
MemoryLimitMiB = 256,
Environment = new Dictionary<string, string> { { "name", "TRIGGER" }, { "value", "CloudWatch Events" } }
},
Schedule = Schedule.Expression("rate(1 minute)"),
Enabled = true,
RuleName = "sample-scheduled-task-rule"
});
Cluster cluster;
var scheduledFargateTask = new ScheduledFargateTask(this, "ScheduledFargateTask", new ScheduledFargateTaskProps {
Cluster = cluster,
ScheduledFargateTaskImageOptions = new ScheduledFargateTaskImageOptions {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
MemoryLimitMiB = 512
},
Schedule = Schedule.Expression("rate(1 minute)"),
PlatformVersion = FargatePlatformVersion.LATEST
});
Additional Examples
In addition to using the constructs, users can also add logic to customize these constructs:
Configure HTTPS on an ApplicationLoadBalancedFargateService
using Amazon.CDK.AWS.Route53;
using Amazon.CDK.AWS.CertificateManager;
using Amazon.CDK.AWS.ElasticLoadBalancingV2;
Vpc vpc;
Cluster cluster;
var domainZone = HostedZone.FromLookup(this, "Zone", new HostedZoneProviderProps { DomainName = "example.com" });
var certificate = Certificate.FromCertificateArn(this, "Cert", "arn:aws:acm:us-east-1:123456:certificate/abcdefg");
var loadBalancedFargateService = new ApplicationLoadBalancedFargateService(this, "Service", new ApplicationLoadBalancedFargateServiceProps {
Vpc = vpc,
Cluster = cluster,
Certificate = certificate,
SslPolicy = SslPolicy.RECOMMENDED,
DomainName = "api.example.com",
DomainZone = domainZone,
RedirectHTTP = true,
TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
}
});
Set capacityProviderStrategies for ApplicationLoadBalancedFargateService
Cluster cluster;
cluster.EnableFargateCapacityProviders();
var loadBalancedFargateService = new ApplicationLoadBalancedFargateService(this, "Service", new ApplicationLoadBalancedFargateServiceProps {
Cluster = cluster,
TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
},
CapacityProviderStrategies = new [] { new CapacityProviderStrategy {
CapacityProvider = "FARGATE_SPOT",
Weight = 2,
Base = 0
}, new CapacityProviderStrategy {
CapacityProvider = "FARGATE",
Weight = 1,
Base = 1
} }
});
Add Schedule-Based Auto-Scaling to an ApplicationLoadBalancedFargateService
Cluster cluster;
var loadBalancedFargateService = new ApplicationLoadBalancedFargateService(this, "Service", new ApplicationLoadBalancedFargateServiceProps {
Cluster = cluster,
MemoryLimitMiB = 1024,
DesiredCount = 1,
Cpu = 512,
TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
}
});
var scalableTarget = loadBalancedFargateService.Service.AutoScaleTaskCount(new EnableScalingProps {
MinCapacity = 5,
MaxCapacity = 20
});
scalableTarget.ScaleOnSchedule("DaytimeScaleDown", new ScalingSchedule {
Schedule = Schedule.Cron(new CronOptions { Hour = "8", Minute = "0" }),
MinCapacity = 1
});
scalableTarget.ScaleOnSchedule("EveningRushScaleUp", new ScalingSchedule {
Schedule = Schedule.Cron(new CronOptions { Hour = "20", Minute = "0" }),
MinCapacity = 10
});
Add Metric-Based Auto-Scaling to an ApplicationLoadBalancedFargateService
Cluster cluster;
var loadBalancedFargateService = new ApplicationLoadBalancedFargateService(this, "Service", new ApplicationLoadBalancedFargateServiceProps {
Cluster = cluster,
MemoryLimitMiB = 1024,
DesiredCount = 1,
Cpu = 512,
TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
}
});
var scalableTarget = loadBalancedFargateService.Service.AutoScaleTaskCount(new EnableScalingProps {
MinCapacity = 1,
MaxCapacity = 20
});
scalableTarget.ScaleOnCpuUtilization("CpuScaling", new CpuUtilizationScalingProps {
TargetUtilizationPercent = 50
});
scalableTarget.ScaleOnMemoryUtilization("MemoryScaling", new MemoryUtilizationScalingProps {
TargetUtilizationPercent = 50
});
Change the default Deployment Controller
Cluster cluster;
var loadBalancedFargateService = new ApplicationLoadBalancedFargateService(this, "Service", new ApplicationLoadBalancedFargateServiceProps {
Cluster = cluster,
MemoryLimitMiB = 1024,
DesiredCount = 1,
Cpu = 512,
TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
},
DeploymentController = new DeploymentController {
Type = DeploymentControllerType.CODE_DEPLOY
}
});
Deployment circuit breaker and rollback
Amazon ECS deployment circuit breaker
automatically rolls back unhealthy service deployments without the need for manual intervention. Use circuitBreaker
to enable
deployment circuit breaker and optionally enable rollback
for automatic rollback. See Using the deployment circuit breaker
for more details.
Cluster cluster;
var service = new ApplicationLoadBalancedFargateService(this, "Service", new ApplicationLoadBalancedFargateServiceProps {
Cluster = cluster,
MemoryLimitMiB = 1024,
DesiredCount = 1,
Cpu = 512,
TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
},
CircuitBreaker = new DeploymentCircuitBreaker { Rollback = true }
});
Set deployment configuration on QueueProcessingService
Cluster cluster;
var queueProcessingFargateService = new QueueProcessingFargateService(this, "Service", new QueueProcessingFargateServiceProps {
Cluster = cluster,
MemoryLimitMiB = 512,
Image = ContainerImage.FromRegistry("test"),
Command = new [] { "-c", "4", "amazon.com" },
EnableLogging = false,
DesiredTaskCount = 2,
Environment = new Dictionary<string, object> { },
MaxScalingCapacity = 5,
MaxHealthyPercent = 200,
MinHealthyPercent = 66
});
Set taskSubnets and securityGroups for QueueProcessingFargateService
Vpc vpc;
SecurityGroup securityGroup;
var queueProcessingFargateService = new QueueProcessingFargateService(this, "Service", new QueueProcessingFargateServiceProps {
Vpc = vpc,
MemoryLimitMiB = 512,
Image = ContainerImage.FromRegistry("test"),
SecurityGroups = new [] { securityGroup },
TaskSubnets = new SubnetSelection { SubnetType = SubnetType.PRIVATE_ISOLATED }
});
Define tasks with public IPs for QueueProcessingFargateService
Vpc vpc;
var queueProcessingFargateService = new QueueProcessingFargateService(this, "Service", new QueueProcessingFargateServiceProps {
Vpc = vpc,
MemoryLimitMiB = 512,
Image = ContainerImage.FromRegistry("test"),
AssignPublicIp = true
});
Define tasks with custom queue parameters for QueueProcessingFargateService
Vpc vpc;
var queueProcessingFargateService = new QueueProcessingFargateService(this, "Service", new QueueProcessingFargateServiceProps {
Vpc = vpc,
MemoryLimitMiB = 512,
Image = ContainerImage.FromRegistry("test"),
MaxReceiveCount = 42,
RetentionPeriod = Duration.Days(7),
VisibilityTimeout = Duration.Minutes(5)
});
Set cooldown for QueueProcessingFargateService
The cooldown period is the amount of time to wait for a previous scaling activity to take effect.
To specify something other than the default cooldown period of 300 seconds, use the cooldown
parameter:
Vpc vpc;
var queueProcessingFargateService = new QueueProcessingFargateService(this, "Service", new QueueProcessingFargateServiceProps {
Vpc = vpc,
MemoryLimitMiB = 512,
Image = ContainerImage.FromRegistry("test"),
AssignPublicIp = true,
Cooldown = Duration.Seconds(500)
});
Set capacityProviderStrategies for QueueProcessingFargateService
Cluster cluster;
cluster.EnableFargateCapacityProviders();
var queueProcessingFargateService = new QueueProcessingFargateService(this, "Service", new QueueProcessingFargateServiceProps {
Cluster = cluster,
MemoryLimitMiB = 512,
Image = ContainerImage.FromRegistry("test"),
CapacityProviderStrategies = new [] { new CapacityProviderStrategy {
CapacityProvider = "FARGATE_SPOT",
Weight = 2
}, new CapacityProviderStrategy {
CapacityProvider = "FARGATE",
Weight = 1
} }
});
Set a custom container-level Healthcheck for QueueProcessingFargateService
Vpc vpc;
SecurityGroup securityGroup;
var queueProcessingFargateService = new QueueProcessingFargateService(this, "Service", new QueueProcessingFargateServiceProps {
Vpc = vpc,
MemoryLimitMiB = 512,
Image = ContainerImage.FromRegistry("test"),
HealthCheck = new HealthCheck {
Command = new [] { "CMD-SHELL", "curl -f http://localhost/ || exit 1" },
// the properties below are optional
Interval = Duration.Minutes(30),
Retries = 123,
StartPeriod = Duration.Minutes(30),
Timeout = Duration.Minutes(30)
}
});
Set capacityProviderStrategies for QueueProcessingEc2Service
using Amazon.CDK.AWS.AutoScaling;
var vpc = new Vpc(this, "Vpc", new VpcProps { MaxAzs = 1 });
var cluster = new Cluster(this, "EcsCluster", new ClusterProps { Vpc = vpc });
var autoScalingGroup = new AutoScalingGroup(this, "asg", new AutoScalingGroupProps {
Vpc = vpc,
InstanceType = InstanceType.Of(InstanceClass.BURSTABLE2, InstanceSize.MICRO),
MachineImage = EcsOptimizedImage.AmazonLinux2()
});
var capacityProvider = new AsgCapacityProvider(this, "provider", new AsgCapacityProviderProps {
AutoScalingGroup = autoScalingGroup
});
cluster.AddAsgCapacityProvider(capacityProvider);
var queueProcessingEc2Service = new QueueProcessingEc2Service(this, "Service", new QueueProcessingEc2ServiceProps {
Cluster = cluster,
MemoryLimitMiB = 512,
Image = ContainerImage.FromRegistry("test"),
CapacityProviderStrategies = new [] { new CapacityProviderStrategy {
CapacityProvider = capacityProvider.CapacityProviderName
} }
});
Select specific vpc subnets for ApplicationLoadBalancedFargateService
Cluster cluster;
var loadBalancedFargateService = new ApplicationLoadBalancedFargateService(this, "Service", new ApplicationLoadBalancedFargateServiceProps {
Cluster = cluster,
MemoryLimitMiB = 1024,
DesiredCount = 1,
Cpu = 512,
TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
},
TaskSubnets = new SubnetSelection {
Subnets = new [] { Subnet.FromSubnetId(this, "subnet", "VpcISOLATEDSubnet1Subnet80F07FA0") }
}
});
Select idleTimeout for ApplicationLoadBalancedFargateService
Cluster cluster;
var loadBalancedFargateService = new ApplicationLoadBalancedFargateService(this, "Service", new ApplicationLoadBalancedFargateServiceProps {
Cluster = cluster,
MemoryLimitMiB = 1024,
DesiredCount = 1,
Cpu = 512,
TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
},
IdleTimeout = Duration.Seconds(120)
});
Select idleTimeout for ApplicationMultipleTargetGroupsFargateService
using Amazon.CDK.AWS.CertificateManager;
using Amazon.CDK.AWS.EC2;
using Amazon.CDK.AWS.ECS;
using Amazon.CDK.AWS.ElasticLoadBalancingV2;
using Amazon.CDK.AWS.Route53;
var vpc = new Vpc(this, "Vpc", new VpcProps { MaxAzs = 1 });
var loadBalancedFargateService = new ApplicationMultipleTargetGroupsFargateService(this, "myService", new ApplicationMultipleTargetGroupsFargateServiceProps {
Cluster = new Cluster(this, "EcsCluster", new ClusterProps { Vpc = vpc }),
MemoryLimitMiB = 256,
TaskImageOptions = new ApplicationLoadBalancedTaskImageProps {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
},
EnableExecuteCommand = true,
LoadBalancers = new [] { new ApplicationLoadBalancerProps {
Name = "lb",
IdleTimeout = Duration.Seconds(400),
DomainName = "api.example.com",
DomainZone = new PublicHostedZone(this, "HostedZone", new PublicHostedZoneProps { ZoneName = "example.com" }),
Listeners = new [] { new ApplicationListenerProps {
Name = "listener",
Protocol = ApplicationProtocol.HTTPS,
Certificate = Certificate.FromCertificateArn(this, "Cert", "helloworld"),
SslPolicy = SslPolicy.TLS12_EXT
} }
}, new ApplicationLoadBalancerProps {
Name = "lb2",
IdleTimeout = Duration.Seconds(120),
DomainName = "frontend.com",
DomainZone = new PublicHostedZone(this, "HostedZone", new PublicHostedZoneProps { ZoneName = "frontend.com" }),
Listeners = new [] { new ApplicationListenerProps {
Name = "listener2",
Protocol = ApplicationProtocol.HTTPS,
Certificate = Certificate.FromCertificateArn(this, "Cert2", "helloworld"),
SslPolicy = SslPolicy.TLS12_EXT
} }
} },
TargetGroups = new [] { new ApplicationTargetProps {
ContainerPort = 80,
Listener = "listener"
}, new ApplicationTargetProps {
ContainerPort = 90,
PathPattern = "a/b/c",
Priority = 10,
Listener = "listener"
}, new ApplicationTargetProps {
ContainerPort = 443,
Listener = "listener2"
}, new ApplicationTargetProps {
ContainerPort = 80,
PathPattern = "a/b/c",
Priority = 10,
Listener = "listener2"
} }
});
Set health checks for ApplicationMultipleTargetGroupsFargateService
using Amazon.CDK.AWS.CertificateManager;
using Amazon.CDK.AWS.EC2;
using Amazon.CDK.AWS.ECS;
using Amazon.CDK.AWS.ElasticLoadBalancingV2;
using Amazon.CDK.AWS.Route53;
var vpc = new Vpc(this, "Vpc", new VpcProps { MaxAzs = 1 });
var loadBalancedFargateService = new ApplicationMultipleTargetGroupsFargateService(this, "myService", new ApplicationMultipleTargetGroupsFargateServiceProps {
Cluster = new Cluster(this, "EcsCluster", new ClusterProps { Vpc = vpc }),
MemoryLimitMiB = 256,
TaskImageOptions = new ApplicationLoadBalancedTaskImageProps {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
},
EnableExecuteCommand = true,
LoadBalancers = new [] { new ApplicationLoadBalancerProps {
Name = "lb",
IdleTimeout = Duration.Seconds(400),
DomainName = "api.example.com",
DomainZone = new PublicHostedZone(this, "HostedZone", new PublicHostedZoneProps { ZoneName = "example.com" }),
Listeners = new [] { new ApplicationListenerProps {
Name = "listener",
Protocol = ApplicationProtocol.HTTPS,
Certificate = Certificate.FromCertificateArn(this, "Cert", "helloworld"),
SslPolicy = SslPolicy.TLS12_EXT
} }
}, new ApplicationLoadBalancerProps {
Name = "lb2",
IdleTimeout = Duration.Seconds(120),
DomainName = "frontend.com",
DomainZone = new PublicHostedZone(this, "HostedZone", new PublicHostedZoneProps { ZoneName = "frontend.com" }),
Listeners = new [] { new ApplicationListenerProps {
Name = "listener2",
Protocol = ApplicationProtocol.HTTPS,
Certificate = Certificate.FromCertificateArn(this, "Cert2", "helloworld"),
SslPolicy = SslPolicy.TLS12_EXT
} }
} },
TargetGroups = new [] { new ApplicationTargetProps {
ContainerPort = 80,
Listener = "listener"
}, new ApplicationTargetProps {
ContainerPort = 90,
PathPattern = "a/b/c",
Priority = 10,
Listener = "listener"
}, new ApplicationTargetProps {
ContainerPort = 443,
Listener = "listener2"
}, new ApplicationTargetProps {
ContainerPort = 80,
PathPattern = "a/b/c",
Priority = 10,
Listener = "listener2"
} }
});
loadBalancedFargateService.TargetGroups[0].ConfigureHealthCheck(new HealthCheck {
Port = "8050",
Protocol = Protocol.HTTP,
HealthyThresholdCount = 2,
UnhealthyThresholdCount = 2,
Timeout = Duration.Seconds(10),
Interval = Duration.Seconds(30),
HealthyHttpCodes = "200"
});
loadBalancedFargateService.TargetGroups[1].ConfigureHealthCheck(new HealthCheck {
Port = "8050",
Protocol = Protocol.HTTP,
HealthyThresholdCount = 2,
UnhealthyThresholdCount = 2,
Timeout = Duration.Seconds(10),
Interval = Duration.Seconds(30),
HealthyHttpCodes = "200"
});
Set runtimePlatform for ApplicationLoadBalancedFargateService
Cluster cluster;
var applicationLoadBalancedFargateService = new ApplicationLoadBalancedFargateService(this, "Service", new ApplicationLoadBalancedFargateServiceProps {
Cluster = cluster,
MemoryLimitMiB = 512,
TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
},
RuntimePlatform = new RuntimePlatform {
CpuArchitecture = CpuArchitecture.ARM64,
OperatingSystemFamily = OperatingSystemFamily.LINUX
}
});
Set PlatformVersion for ScheduledFargateTask
Cluster cluster;
var scheduledFargateTask = new ScheduledFargateTask(this, "ScheduledFargateTask", new ScheduledFargateTaskProps {
Cluster = cluster,
ScheduledFargateTaskImageOptions = new ScheduledFargateTaskImageOptions {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
MemoryLimitMiB = 512
},
Schedule = Schedule.Expression("rate(1 minute)"),
PlatformVersion = FargatePlatformVersion.VERSION1_4
});
Set SecurityGroups for ScheduledFargateTask
var vpc = new Vpc(this, "Vpc", new VpcProps { MaxAzs = 1 });
var cluster = new Cluster(this, "EcsCluster", new ClusterProps { Vpc = vpc });
var securityGroup = new SecurityGroup(this, "SG", new SecurityGroupProps { Vpc = vpc });
var scheduledFargateTask = new ScheduledFargateTask(this, "ScheduledFargateTask", new ScheduledFargateTaskProps {
Cluster = cluster,
ScheduledFargateTaskImageOptions = new ScheduledFargateTaskImageOptions {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
MemoryLimitMiB = 512
},
Schedule = Schedule.Expression("rate(1 minute)"),
SecurityGroups = new [] { securityGroup }
});
Deploy application and metrics sidecar
The following is an example of deploying an application along with a metrics sidecar container that utilizes dockerLabels
for discovery:
Cluster cluster;
Vpc vpc;
var service = new ApplicationLoadBalancedFargateService(this, "Service", new ApplicationLoadBalancedFargateServiceProps {
Cluster = cluster,
Vpc = vpc,
DesiredCount = 1,
TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
DockerLabels = new Dictionary<string, string> {
{ "application.label.one", "first_label" },
{ "application.label.two", "second_label" }
}
}
});
service.TaskDefinition.AddContainer("Sidecar", new ContainerDefinitionOptions {
Image = ContainerImage.FromRegistry("example/metrics-sidecar")
});
Select specific load balancer name ApplicationLoadBalancedFargateService
Cluster cluster;
var loadBalancedFargateService = new ApplicationLoadBalancedFargateService(this, "Service", new ApplicationLoadBalancedFargateServiceProps {
Cluster = cluster,
MemoryLimitMiB = 1024,
DesiredCount = 1,
Cpu = 512,
TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
},
TaskSubnets = new SubnetSelection {
Subnets = new [] { Subnet.FromSubnetId(this, "subnet", "VpcISOLATEDSubnet1Subnet80F07FA0") }
},
LoadBalancerName = "application-lb-name"
});
ECS Exec
You can use ECS Exec to run commands in or get a shell to a container running on an Amazon EC2 instance or on
AWS Fargate. Enable ECS Exec, by setting enableExecuteCommand
to true
.
ECS Exec is supported by all Services i.e. ApplicationLoadBalanced(Fargate|Ec2)Service
, ApplicationMultipleTargetGroups(Fargate|Ec2)Service
, NetworkLoadBalanced(Fargate|Ec2)Service
, NetworkMultipleTargetGroups(Fargate|Ec2)Service
, QueueProcessing(Fargate|Ec2)Service
. It is not supported for ScheduledTask
s.
Read more about ECS Exec in the ECS Developer Guide.
Example:
Cluster cluster;
var loadBalancedFargateService = new ApplicationLoadBalancedFargateService(this, "Service", new ApplicationLoadBalancedFargateServiceProps {
Cluster = cluster,
MemoryLimitMiB = 1024,
DesiredCount = 1,
Cpu = 512,
TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
},
EnableExecuteCommand = true
});
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.
Propagate Tags from task definition for ScheduledFargateTask
For tasks that are defined by a Task Definition, tags applied to the definition will not be applied
to the running task by default. To get this behavior, set propagateTags
to ecs.PropagatedTagSource.TASK_DEFINITION
as
shown below:
using Amazon.CDK;
var vpc = new Vpc(this, "Vpc", new VpcProps { MaxAzs = 1 });
var cluster = new Cluster(this, "EcsCluster", new ClusterProps { Vpc = vpc });
var taskDefinition = new FargateTaskDefinition(this, "TaskDef", new FargateTaskDefinitionProps {
MemoryLimitMiB = 512,
Cpu = 256
});
taskDefinition.AddContainer("WebContainer", new ContainerDefinitionOptions {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
});
Tags.Of(taskDefinition).Add("my-tag", "my-tag-value");
var scheduledFargateTask = new ScheduledFargateTask(this, "ScheduledFargateTask", new ScheduledFargateTaskProps {
Cluster = cluster,
TaskDefinition = taskDefinition,
Schedule = Schedule.Expression("rate(1 minute)"),
PropagateTags = PropagatedTagSource.TASK_DEFINITION
});
Pass a list of tags for ScheduledFargateTask
You can pass a list of tags to be applied to a Fargate task directly. These tags are in addition to any tags
that could be applied to the task definition and propagated using the propagateTags
attribute.
var vpc = new Vpc(this, "Vpc", new VpcProps { MaxAzs = 1 });
var cluster = new Cluster(this, "EcsCluster", new ClusterProps { Vpc = vpc });
var scheduledFargateTask = new ScheduledFargateTask(this, "ScheduledFargateTask", new ScheduledFargateTaskProps {
Cluster = cluster,
ScheduledFargateTaskImageOptions = new ScheduledFargateTaskImageOptions {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample"),
MemoryLimitMiB = 512
},
Schedule = Schedule.Expression("rate(1 minute)"),
Tags = new [] { new Tag {
Key = "my-tag",
Value = "my-tag-value"
} }
});
Use custom ephemeral storage for ECS Fargate tasks
You can pass a custom ephemeral storage (21GiB - 200GiB) to ECS Fargate tasks on Fargate Platform Version 1.4.0 or later.
var vpc = new Vpc(this, "Vpc", new VpcProps { MaxAzs = 2, RestrictDefaultSecurityGroup = false });
var cluster = new Cluster(this, "FargateCluster", new ClusterProps { Vpc = vpc });
var applicationLoadBalancedFargateService = new ApplicationLoadBalancedFargateService(this, "ALBFargateServiceWithCustomEphemeralStorage", new ApplicationLoadBalancedFargateServiceProps {
Cluster = cluster,
MemoryLimitMiB = 1024,
Cpu = 512,
EphemeralStorageGiB = 21,
TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
}
});
var networkLoadBalancedFargateService = new NetworkLoadBalancedFargateService(this, "NLBFargateServiceWithCustomEphemeralStorage", new NetworkLoadBalancedFargateServiceProps {
Cluster = cluster,
MemoryLimitMiB = 1024,
Cpu = 512,
EphemeralStorageGiB = 200,
TaskImageOptions = new NetworkLoadBalancedTaskImageOptions {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
}
});
Set securityGroups for NetworkLoadBalancedFargateService
Vpc vpc;
SecurityGroup securityGroup;
var queueProcessingFargateService = new NetworkLoadBalancedFargateService(this, "Service", new NetworkLoadBalancedFargateServiceProps {
Vpc = vpc,
MemoryLimitMiB = 512,
TaskImageOptions = new NetworkLoadBalancedTaskImageOptions {
Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample")
},
SecurityGroups = new [] { securityGroup }
});
Classes
ApplicationListenerProps | Properties to define an application listener. |
ApplicationLoadBalancedEc2Service | An EC2 service running on an ECS cluster fronted by an application load balancer. |
ApplicationLoadBalancedEc2ServiceProps | The properties for the ApplicationLoadBalancedEc2Service service. |
ApplicationLoadBalancedFargateService | A Fargate service running on an ECS cluster fronted by an application load balancer. |
ApplicationLoadBalancedFargateServiceProps | The properties for the ApplicationLoadBalancedFargateService service. |
ApplicationLoadBalancedServiceBase | The base class for ApplicationLoadBalancedEc2Service and ApplicationLoadBalancedFargateService services. |
ApplicationLoadBalancedServiceBaseProps | The properties for the base ApplicationLoadBalancedEc2Service or ApplicationLoadBalancedFargateService service. |
ApplicationLoadBalancedServiceRecordType | Describes the type of DNS record the service should create. |
ApplicationLoadBalancedTaskImageOptions | |
ApplicationLoadBalancedTaskImageProps | Options for configuring a new container. |
ApplicationLoadBalancerProps | Properties to define an application load balancer. |
ApplicationMultipleTargetGroupsEc2Service | An EC2 service running on an ECS cluster fronted by an application load balancer. |
ApplicationMultipleTargetGroupsEc2ServiceProps | The properties for the ApplicationMultipleTargetGroupsEc2Service service. |
ApplicationMultipleTargetGroupsFargateService | A Fargate service running on an ECS cluster fronted by an application load balancer. |
ApplicationMultipleTargetGroupsFargateServiceProps | The properties for the ApplicationMultipleTargetGroupsFargateService service. |
ApplicationMultipleTargetGroupsServiceBase | The base class for ApplicationMultipleTargetGroupsEc2Service and ApplicationMultipleTargetGroupsFargateService classes. |
ApplicationMultipleTargetGroupsServiceBaseProps | The properties for the base ApplicationMultipleTargetGroupsEc2Service or ApplicationMultipleTargetGroupsFargateService service. |
ApplicationTargetProps | Properties to define an application target group. |
FargateServiceBaseProps | |
NetworkListenerProps | Properties to define an network listener. |
NetworkLoadBalancedEc2Service | An EC2 service running on an ECS cluster fronted by a network load balancer. |
NetworkLoadBalancedEc2ServiceProps | The properties for the NetworkLoadBalancedEc2Service service. |
NetworkLoadBalancedFargateService | A Fargate service running on an ECS cluster fronted by a network load balancer. |
NetworkLoadBalancedFargateServiceProps | The properties for the NetworkLoadBalancedFargateService service. |
NetworkLoadBalancedServiceBase | The base class for NetworkLoadBalancedEc2Service and NetworkLoadBalancedFargateService services. |
NetworkLoadBalancedServiceBaseProps | The properties for the base NetworkLoadBalancedEc2Service or NetworkLoadBalancedFargateService service. |
NetworkLoadBalancedServiceRecordType | Describes the type of DNS record the service should create. |
NetworkLoadBalancedTaskImageOptions | |
NetworkLoadBalancedTaskImageProps | Options for configuring a new container. |
NetworkLoadBalancerProps | Properties to define an network load balancer. |
NetworkMultipleTargetGroupsEc2Service | An EC2 service running on an ECS cluster fronted by a network load balancer. |
NetworkMultipleTargetGroupsEc2ServiceProps | The properties for the NetworkMultipleTargetGroupsEc2Service service. |
NetworkMultipleTargetGroupsFargateService | A Fargate service running on an ECS cluster fronted by a network load balancer. |
NetworkMultipleTargetGroupsFargateServiceProps | The properties for the NetworkMultipleTargetGroupsFargateService service. |
NetworkMultipleTargetGroupsServiceBase | The base class for NetworkMultipleTargetGroupsEc2Service and NetworkMultipleTargetGroupsFargateService classes. |
NetworkMultipleTargetGroupsServiceBaseProps | The properties for the base NetworkMultipleTargetGroupsEc2Service or NetworkMultipleTargetGroupsFargateService service. |
NetworkTargetProps | Properties to define a network load balancer target group. |
QueueProcessingEc2Service | Class to create a queue processing EC2 service. |
QueueProcessingEc2ServiceProps | The properties for the QueueProcessingEc2Service service. |
QueueProcessingFargateService | Class to create a queue processing Fargate service. |
QueueProcessingFargateServiceProps | The properties for the QueueProcessingFargateService service. |
QueueProcessingServiceBase | The base class for QueueProcessingEc2Service and QueueProcessingFargateService services. |
QueueProcessingServiceBaseProps | The properties for the base QueueProcessingEc2Service or QueueProcessingFargateService service. |
ScheduledEc2Task | A scheduled EC2 task that will be initiated off of CloudWatch Events. |
ScheduledEc2TaskDefinitionOptions | The properties for the ScheduledEc2Task using a task definition. |
ScheduledEc2TaskImageOptions | The properties for the ScheduledEc2Task using an image. |
ScheduledEc2TaskProps | The properties for the ScheduledEc2Task task. |
ScheduledFargateTask | A scheduled Fargate task that will be initiated off of CloudWatch Events. |
ScheduledFargateTaskDefinitionOptions | The properties for the ScheduledFargateTask using a task definition. |
ScheduledFargateTaskImageOptions | The properties for the ScheduledFargateTask using an image. |
ScheduledFargateTaskProps | The properties for the ScheduledFargateTask task. |
ScheduledTaskBase | The base class for ScheduledEc2Task and ScheduledFargateTask tasks. |
ScheduledTaskBaseProps | The properties for the base ScheduledEc2Task or ScheduledFargateTask task. |
ScheduledTaskImageProps |
Interfaces
IApplicationListenerProps | Properties to define an application listener. |
IApplicationLoadBalancedEc2ServiceProps | The properties for the ApplicationLoadBalancedEc2Service service. |
IApplicationLoadBalancedFargateServiceProps | The properties for the ApplicationLoadBalancedFargateService service. |
IApplicationLoadBalancedServiceBaseProps | The properties for the base ApplicationLoadBalancedEc2Service or ApplicationLoadBalancedFargateService service. |
IApplicationLoadBalancedTaskImageOptions | |
IApplicationLoadBalancedTaskImageProps | Options for configuring a new container. |
IApplicationLoadBalancerProps | Properties to define an application load balancer. |
IApplicationMultipleTargetGroupsEc2ServiceProps | The properties for the ApplicationMultipleTargetGroupsEc2Service service. |
IApplicationMultipleTargetGroupsFargateServiceProps | The properties for the ApplicationMultipleTargetGroupsFargateService service. |
IApplicationMultipleTargetGroupsServiceBaseProps | The properties for the base ApplicationMultipleTargetGroupsEc2Service or ApplicationMultipleTargetGroupsFargateService service. |
IApplicationTargetProps | Properties to define an application target group. |
IFargateServiceBaseProps | |
INetworkListenerProps | Properties to define an network listener. |
INetworkLoadBalancedEc2ServiceProps | The properties for the NetworkLoadBalancedEc2Service service. |
INetworkLoadBalancedFargateServiceProps | The properties for the NetworkLoadBalancedFargateService service. |
INetworkLoadBalancedServiceBaseProps | The properties for the base NetworkLoadBalancedEc2Service or NetworkLoadBalancedFargateService service. |
INetworkLoadBalancedTaskImageOptions | |
INetworkLoadBalancedTaskImageProps | Options for configuring a new container. |
INetworkLoadBalancerProps | Properties to define an network load balancer. |
INetworkMultipleTargetGroupsEc2ServiceProps | The properties for the NetworkMultipleTargetGroupsEc2Service service. |
INetworkMultipleTargetGroupsFargateServiceProps | The properties for the NetworkMultipleTargetGroupsFargateService service. |
INetworkMultipleTargetGroupsServiceBaseProps | The properties for the base NetworkMultipleTargetGroupsEc2Service or NetworkMultipleTargetGroupsFargateService service. |
INetworkTargetProps | Properties to define a network load balancer target group. |
IQueueProcessingEc2ServiceProps | The properties for the QueueProcessingEc2Service service. |
IQueueProcessingFargateServiceProps | The properties for the QueueProcessingFargateService service. |
IQueueProcessingServiceBaseProps | The properties for the base QueueProcessingEc2Service or QueueProcessingFargateService service. |
IScheduledEc2TaskDefinitionOptions | The properties for the ScheduledEc2Task using a task definition. |
IScheduledEc2TaskImageOptions | The properties for the ScheduledEc2Task using an image. |
IScheduledEc2TaskProps | The properties for the ScheduledEc2Task task. |
IScheduledFargateTaskDefinitionOptions | The properties for the ScheduledFargateTask using a task definition. |
IScheduledFargateTaskImageOptions | The properties for the ScheduledFargateTask using an image. |
IScheduledFargateTaskProps | The properties for the ScheduledFargateTask task. |
IScheduledTaskBaseProps | The properties for the base ScheduledEc2Task or ScheduledFargateTask task. |
IScheduledTaskImageProps |