54 types
This library provides higher-level Amazon ECS constructs which follow common architectural patterns. It contains:
To define an Amazon ECS service that is behind an application load balancer, instantiate one of the following:
ApplicationLoadBalancedEc2Servicecluster = nil # AWSCDK::ECS::Cluster
load_balanced_ecs_service = AWSCDK::ECSPatterns::ApplicationLoadBalancedEC2Service.new(self, "Service", {
cluster: cluster,
memory_limit_mi_b: 1024,
task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("test"),
environment: {
TEST_ENVIRONMENT_VARIABLE1: "test environment variable 1 value",
TEST_ENVIRONMENT_VARIABLE2: "test environment variable 2 value",
},
command: ["command"],
entry_point: ["entry", "point"],
},
desired_count: 2,
min_healthy_percent: 100,
})
ApplicationLoadBalancedFargateServicecluster = nil # AWSCDK::ECS::Cluster
load_balanced_fargate_service = AWSCDK::ECSPatterns::ApplicationLoadBalancedFargateService.new(self, "Service", {
cluster: cluster,
memory_limit_mi_b: 1024,
cpu: 512,
task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
command: ["command"],
entry_point: ["entry", "point"],
},
container_cpu: 256,
container_memory_limit_mi_b: 512,
min_healthy_percent: 100,
})
load_balanced_fargate_service.target_group.configure_health_check({
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 health_check 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 platform_version property in the constructor.
Fargate services use the default VPC Security Group unless one or more are provided using the security_groups property in the constructor.
Security Considerations: When using custom security groups on your load balancer, the open_listener property controls whether the load balancer listener allows traffic from anywhere on the internet (0.0.0.0/0). By default, open_listener is true, but it will automatically default to false when custom security groups are detected, preventing unintended internet exposure. You can always explicitly set openListener: true to override this behavior if needed.
By setting redirect_http to true, CDK will automatically create a listener on port 80 that redirects HTTP traffic to the HTTPS port.
If you specify the option record_type you can decide if you want the construct to use CNAME or Route53-Aliases as record sets.
To set the minimum number of CPU units to reserve for the container, you can use the container_cpu property.
To set the amount of memory (in MiB) to provide to the container, you can use the container_memory_limit_mib property.
If you need to encrypt the traffic between the load balancer and the ECS tasks, you can set the target_protocol to HTTPS.
Additionally, if more than one application target group are needed, instantiate one of the following:
ApplicationMultipleTargetGroupsEc2Service# One application load balancer with one listener and two target groups.
cluster = nil # AWSCDK::ECS::Cluster
load_balanced_ec2_service = AWSCDK::ECSPatterns::ApplicationMultipleTargetGroupsEC2Service.new(self, "Service", {
cluster: cluster,
memory_limit_mi_b: 256,
task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
},
target_groups: [
{
container_port: 80,
},
{
container_port: 90,
path_pattern: "a/b/c",
priority: 10,
},
],
})
ApplicationMultipleTargetGroupsFargateService# One application load balancer with one listener and two target groups.
cluster = nil # AWSCDK::ECS::Cluster
load_balanced_fargate_service = AWSCDK::ECSPatterns::ApplicationMultipleTargetGroupsFargateService.new(self, "Service", {
cluster: cluster,
memory_limit_mi_b: 1024,
cpu: 512,
task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
},
target_groups: [
{
container_port: 80,
},
{
container_port: 90,
path_pattern: "a/b/c",
priority: 10,
},
],
})
To define an Amazon ECS service that is behind a network load balancer, instantiate one of the following:
NetworkLoadBalancedEc2Servicecluster = nil # AWSCDK::ECS::Cluster
load_balanced_ecs_service = AWSCDK::ECSPatterns::NetworkLoadBalancedEC2Service.new(self, "Service", {
cluster: cluster,
memory_limit_mi_b: 1024,
task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("test"),
environment: {
TEST_ENVIRONMENT_VARIABLE1: "test environment variable 1 value",
TEST_ENVIRONMENT_VARIABLE2: "test environment variable 2 value",
},
},
desired_count: 2,
min_healthy_percent: 100,
})
NetworkLoadBalancedFargateServicecluster = nil # AWSCDK::ECS::Cluster
load_balanced_fargate_service = AWSCDK::ECSPatterns::NetworkLoadBalancedFargateService.new(self, "Service", {
cluster: cluster,
memory_limit_mi_b: 1024,
cpu: 512,
task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
},
min_healthy_percent: 100,
})
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 record_type 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 = nil # AWSCDK::ECS::Cluster
load_balanced_ec2_service = AWSCDK::ECSPatterns::NetworkMultipleTargetGroupsEC2Service.new(self, "Service", {
cluster: cluster,
memory_limit_mi_b: 256,
task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
},
load_balancers: [
{
name: "lb1",
listeners: [
{
name: "listener1",
},
],
},
{
name: "lb2",
listeners: [
{
name: "listener2",
},
],
},
],
target_groups: [
{
container_port: 80,
listener: "listener1",
},
{
container_port: 90,
listener: "listener2",
},
],
})
# Two network load balancers, each with their own listener and target group.
cluster = nil # AWSCDK::ECS::Cluster
load_balanced_fargate_service = AWSCDK::ECSPatterns::NetworkMultipleTargetGroupsFargateService.new(self, "Service", {
cluster: cluster,
memory_limit_mi_b: 512,
task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
},
load_balancers: [
{
name: "lb1",
listeners: [
{
name: "listener1",
},
],
},
{
name: "lb2",
listeners: [
{
name: "listener2",
},
],
},
],
target_groups: [
{
container_port: 80,
listener: "listener1",
},
{
container_port: 90,
listener: "listener2",
},
],
min_healthy_percent: 100,
max_healthy_percent: 200,
})
To define a service that creates a queue and reads from that queue, instantiate one of the following:
QueueProcessingEc2Servicecluster = nil # AWSCDK::ECS::Cluster
queue_processing_ec2_service = AWSCDK::ECSPatterns::QueueProcessingEC2Service.new(self, "Service", {
cluster: cluster,
memory_limit_mi_b: 1024,
image: AWSCDK::ECS::ContainerImage.from_registry("test"),
command: ["-c", "4", "amazon.com"],
enable_logging: false,
desired_task_count: 2,
environment: {
TEST_ENVIRONMENT_VARIABLE1: "test environment variable 1 value",
TEST_ENVIRONMENT_VARIABLE2: "test environment variable 2 value",
},
max_scaling_capacity: 5,
container_name: "test",
min_healthy_percent: 100,
})
QueueProcessingFargateServicecluster = nil # AWSCDK::ECS::Cluster
queue_processing_fargate_service = AWSCDK::ECSPatterns::QueueProcessingFargateService.new(self, "Service", {
cluster: cluster,
memory_limit_mi_b: 512,
image: AWSCDK::ECS::ContainerImage.from_registry("test"),
command: ["-c", "4", "amazon.com"],
enable_logging: false,
desired_task_count: 2,
environment: {
TEST_ENVIRONMENT_VARIABLE1: "test environment variable 1 value",
TEST_ENVIRONMENT_VARIABLE2: "test environment variable 2 value",
},
max_scaling_capacity: 5,
container_name: "test",
min_healthy_percent: 100,
})
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 = nil # AWSCDK::ECS::Cluster
queue_processing_fargate_service = AWSCDK::ECSPatterns::QueueProcessingFargateService.new(self, "Service", {
cluster: cluster,
memory_limit_mi_b: 512,
image: AWSCDK::ECS::ContainerImage.from_registry("test"),
command: ["-c", "4", "amazon.com"],
enable_logging: false,
desired_task_count: 2,
environment: {
TEST_ENVIRONMENT_VARIABLE1: "test environment variable 1 value",
TEST_ENVIRONMENT_VARIABLE2: "test environment variable 2 value",
},
max_scaling_capacity: 5,
container_name: "test",
min_healthy_percent: 100,
disable_cpu_based_scaling: true,
})
To specify a custom target CPU utilization percentage for the scaling strategy use the cpu_target_utilization_percent property:
cluster = nil # AWSCDK::ECS::Cluster
queue_processing_fargate_service = AWSCDK::ECSPatterns::QueueProcessingFargateService.new(self, "Service", {
cluster: cluster,
memory_limit_mi_b: 512,
image: AWSCDK::ECS::ContainerImage.from_registry("test"),
command: ["-c", "4", "amazon.com"],
enable_logging: false,
desired_task_count: 2,
environment: {},
max_scaling_capacity: 5,
container_name: "test",
min_healthy_percent: 100,
cpu_target_utilization_percent: 90,
})
To define a task that runs periodically, there are 2 options:
ScheduledEc2Task# Instantiate an Amazon EC2 Task to run at a scheduled interval
cluster = nil # AWSCDK::ECS::Cluster
ecs_scheduled_task = AWSCDK::ECSPatterns::ScheduledEC2Task.new(self, "ScheduledTask", {
cluster: cluster,
scheduled_ec2_task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
memory_limit_mi_b: 256,
environment: {name: "TRIGGER", value: "CloudWatch Events"},
},
schedule: AWSCDK::ApplicationAutoScaling::Schedule.expression("rate(1 minute)"),
enabled: true,
rule_name: "sample-scheduled-task-rule",
})
ScheduledFargateTaskcluster = nil # AWSCDK::ECS::Cluster
scheduled_fargate_task = AWSCDK::ECSPatterns::ScheduledFargateTask.new(self, "ScheduledFargateTask", {
cluster: cluster,
scheduled_fargate_task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
memory_limit_mi_b: 512,
},
schedule: AWSCDK::ApplicationAutoScaling::Schedule.expression("rate(1 minute)"),
platform_version: AWSCDK::ECS::FargatePlatformVersion::LATEST,
})
In addition to using the constructs, users can also add logic to customize these constructs:
require 'aws-cdk-lib'
vpc = nil # AWSCDK::EC2::VPC
cluster = nil # AWSCDK::ECS::Cluster
domain_zone = AWSCDK::Route53::HostedZone.from_lookup(self, "Zone", {domain_name: "example.com"})
certificate = AWSCDK::CertificateManager::Certificate.from_certificate_arn(self, "Cert", "arn:aws:acm:us-east-1:123456:certificate/abcdefg")
load_balanced_fargate_service = AWSCDK::ECSPatterns::ApplicationLoadBalancedFargateService.new(self, "Service", {
vpc: vpc,
cluster: cluster,
min_healthy_percent: 100,
certificate: certificate,
ssl_policy: AWSCDK::ElasticLoadBalancingv2::SSLPolicy::RECOMMENDED,
domain_name: "api.example.com",
domain_zone: domain_zone,
redirect_http: true,
task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
},
})
cluster = nil # AWSCDK::ECS::Cluster
cluster.enable_fargate_capacity_providers
load_balanced_fargate_service = AWSCDK::ECSPatterns::ApplicationLoadBalancedFargateService.new(self, "Service", {
cluster: cluster,
task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
},
min_healthy_percent: 100,
capacity_provider_strategies: [
{
capacity_provider: "FARGATE_SPOT",
weight: 2,
base: 0,
},
{
capacity_provider: "FARGATE",
weight: 1,
base: 1,
},
],
})
cluster = nil # AWSCDK::ECS::Cluster
load_balanced_fargate_service = AWSCDK::ECSPatterns::ApplicationLoadBalancedFargateService.new(self, "Service", {
cluster: cluster,
memory_limit_mi_b: 1024,
desired_count: 1,
cpu: 512,
task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
},
min_healthy_percent: 100,
})
scalable_target = load_balanced_fargate_service.service.auto_scale_task_count({
min_capacity: 5,
max_capacity: 20,
})
scalable_target.scale_on_schedule("DaytimeScaleDown", {
schedule: AWSCDK::ApplicationAutoScaling::Schedule.cron({hour: "8", minute: "0"}),
min_capacity: 1,
})
scalable_target.scale_on_schedule("EveningRushScaleUp", {
schedule: AWSCDK::ApplicationAutoScaling::Schedule.cron({hour: "20", minute: "0"}),
min_capacity: 10,
})
cluster = nil # AWSCDK::ECS::Cluster
load_balanced_fargate_service = AWSCDK::ECSPatterns::ApplicationLoadBalancedFargateService.new(self, "Service", {
cluster: cluster,
memory_limit_mi_b: 1024,
desired_count: 1,
cpu: 512,
task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
},
min_healthy_percent: 100,
})
scalable_target = load_balanced_fargate_service.service.auto_scale_task_count({
min_capacity: 1,
max_capacity: 20,
})
scalable_target.scale_on_cpu_utilization("CpuScaling", {
target_utilization_percent: 50,
})
scalable_target.scale_on_memory_utilization("MemoryScaling", {
target_utilization_percent: 50,
})
cluster = nil # AWSCDK::ECS::Cluster
load_balanced_fargate_service = AWSCDK::ECSPatterns::ApplicationLoadBalancedFargateService.new(self, "Service", {
cluster: cluster,
memory_limit_mi_b: 1024,
desired_count: 1,
cpu: 512,
task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
},
min_healthy_percent: 100,
deployment_controller: {
type: AWSCDK::ECS::DeploymentControllerType::CODE_DEPLOY,
},
})
Amazon ECS deployment circuit breaker
automatically rolls back unhealthy service deployments without the need for manual intervention. Use circuit_breaker to enable
deployment circuit breaker and optionally enable rollback for automatic rollback. See Using the deployment circuit breaker
for more details.
cluster = nil # AWSCDK::ECS::Cluster
service = AWSCDK::ECSPatterns::ApplicationLoadBalancedFargateService.new(self, "Service", {
cluster: cluster,
memory_limit_mi_b: 1024,
desired_count: 1,
cpu: 512,
task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
},
min_healthy_percent: 100,
circuit_breaker: {rollback: true},
})
cluster = nil # AWSCDK::ECS::Cluster
queue_processing_fargate_service = AWSCDK::ECSPatterns::QueueProcessingFargateService.new(self, "Service", {
cluster: cluster,
memory_limit_mi_b: 512,
image: AWSCDK::ECS::ContainerImage.from_registry("test"),
command: ["-c", "4", "amazon.com"],
enable_logging: false,
desired_task_count: 2,
environment: {},
max_scaling_capacity: 5,
max_healthy_percent: 200,
min_healthy_percent: 66,
})
vpc = nil # AWSCDK::EC2::VPC
security_group = nil # AWSCDK::EC2::SecurityGroup
queue_processing_fargate_service = AWSCDK::ECSPatterns::QueueProcessingFargateService.new(self, "Service", {
vpc: vpc,
memory_limit_mi_b: 512,
image: AWSCDK::ECS::ContainerImage.from_registry("test"),
min_healthy_percent: 100,
security_groups: [security_group],
task_subnets: {subnet_type: AWSCDK::EC2::SubnetType::PRIVATE_ISOLATED},
})
vpc = nil # AWSCDK::EC2::VPC
queue_processing_fargate_service = AWSCDK::ECSPatterns::QueueProcessingFargateService.new(self, "Service", {
vpc: vpc,
memory_limit_mi_b: 512,
image: AWSCDK::ECS::ContainerImage.from_registry("test"),
min_healthy_percent: 100,
assign_public_ip: true,
})
vpc = nil # AWSCDK::EC2::VPC
queue_processing_fargate_service = AWSCDK::ECSPatterns::QueueProcessingFargateService.new(self, "Service", {
vpc: vpc,
memory_limit_mi_b: 512,
image: AWSCDK::ECS::ContainerImage.from_registry("test"),
min_healthy_percent: 100,
max_receive_count: 42,
retention_period: AWSCDK::Duration.days(7),
visibility_timeout: AWSCDK::Duration.minutes(5),
})
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 = nil # AWSCDK::EC2::VPC
queue_processing_fargate_service = AWSCDK::ECSPatterns::QueueProcessingFargateService.new(self, "Service", {
vpc: vpc,
memory_limit_mi_b: 512,
image: AWSCDK::ECS::ContainerImage.from_registry("test"),
min_healthy_percent: 100,
assign_public_ip: true,
cooldown: AWSCDK::Duration.seconds(500),
})
cluster = nil # AWSCDK::ECS::Cluster
cluster.enable_fargate_capacity_providers
queue_processing_fargate_service = AWSCDK::ECSPatterns::QueueProcessingFargateService.new(self, "Service", {
cluster: cluster,
memory_limit_mi_b: 512,
image: AWSCDK::ECS::ContainerImage.from_registry("test"),
min_healthy_percent: 100,
capacity_provider_strategies: [
{
capacity_provider: "FARGATE_SPOT",
weight: 2,
},
{
capacity_provider: "FARGATE",
weight: 1,
},
],
})
vpc = nil # AWSCDK::EC2::VPC
security_group = nil # AWSCDK::EC2::SecurityGroup
queue_processing_fargate_service = AWSCDK::ECSPatterns::QueueProcessingFargateService.new(self, "Service", {
vpc: vpc,
memory_limit_mi_b: 512,
image: AWSCDK::ECS::ContainerImage.from_registry("test"),
min_healthy_percent: 100,
health_check: {
command: ["CMD-SHELL", "curl -f http://localhost/ || exit 1"],
# the properties below are optional
interval: AWSCDK::Duration.minutes(30),
retries: 123,
start_period: AWSCDK::Duration.minutes(30),
timeout: AWSCDK::Duration.minutes(30),
},
})
require 'aws-cdk-lib'
vpc = AWSCDK::EC2::VPC.new(self, "Vpc", {max_azs: 1})
cluster = AWSCDK::ECS::Cluster.new(self, "EcsCluster", {vpc: vpc})
auto_scaling_group = AWSCDK::Autoscaling::AutoScalingGroup.new(self, "asg", {
vpc: vpc,
instance_type: AWSCDK::EC2::InstanceType.of(AWSCDK::EC2::InstanceClass::BURSTABLE2, AWSCDK::EC2::InstanceSize::MICRO),
machine_image: AWSCDK::ECS::ECSOptimizedImage.amazon_linux2,
})
capacity_provider = AWSCDK::ECS::AsgCapacityProvider.new(self, "provider", {
auto_scaling_group: auto_scaling_group,
})
cluster.add_asg_capacity_provider(capacity_provider)
queue_processing_ec2_service = AWSCDK::ECSPatterns::QueueProcessingEC2Service.new(self, "Service", {
cluster: cluster,
memory_limit_mi_b: 512,
image: AWSCDK::ECS::ContainerImage.from_registry("test"),
min_healthy_percent: 100,
capacity_provider_strategies: [
{
capacity_provider: capacity_provider.capacity_provider_name,
},
],
})
cluster = nil # AWSCDK::ECS::Cluster
load_balanced_fargate_service = AWSCDK::ECSPatterns::ApplicationLoadBalancedFargateService.new(self, "Service", {
cluster: cluster,
memory_limit_mi_b: 1024,
desired_count: 1,
cpu: 512,
task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
},
min_healthy_percent: 100,
task_subnets: {
subnets: [AWSCDK::EC2::Subnet.from_subnet_id(self, "subnet", "VpcISOLATEDSubnet1Subnet80F07FA0")],
},
})
cluster = nil # AWSCDK::ECS::Cluster
load_balanced_fargate_service = AWSCDK::ECSPatterns::ApplicationLoadBalancedFargateService.new(self, "Service", {
cluster: cluster,
memory_limit_mi_b: 1024,
desired_count: 1,
cpu: 512,
task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
},
min_healthy_percent: 100,
idle_timeout: AWSCDK::Duration.seconds(120),
})
require 'aws-cdk-lib'
vpc = AWSCDK::EC2::VPC.new(self, "Vpc", {max_azs: 1})
load_balanced_fargate_service = AWSCDK::ECSPatterns::ApplicationMultipleTargetGroupsFargateService.new(self, "myService", {
cluster: AWSCDK::ECS::Cluster.new(self, "EcsCluster", {vpc: vpc}),
memory_limit_mi_b: 256,
task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
},
enable_execute_command: true,
load_balancers: [
{
name: "lb",
idle_timeout: AWSCDK::Duration.seconds(400),
domain_name: "api.example.com",
domain_zone: AWSCDK::Route53::PublicHostedZone.new(self, "HostedZone", {zone_name: "example.com"}),
listeners: [
{
name: "listener",
protocol: AWSCDK::ElasticLoadBalancingv2::ApplicationProtocol::HTTPS,
certificate: AWSCDK::CertificateManager::Certificate.from_certificate_arn(self, "Cert", "helloworld"),
ssl_policy: AWSCDK::ElasticLoadBalancingv2::SSLPolicy::TLS12_EXT,
},
],
},
{
name: "lb2",
idle_timeout: AWSCDK::Duration.seconds(120),
domain_name: "frontend.com",
domain_zone: AWSCDK::Route53::PublicHostedZone.new(self, "HostedZone", {zone_name: "frontend.com"}),
listeners: [
{
name: "listener2",
protocol: AWSCDK::ElasticLoadBalancingv2::ApplicationProtocol::HTTPS,
certificate: AWSCDK::CertificateManager::Certificate.from_certificate_arn(self, "Cert2", "helloworld"),
ssl_policy: AWSCDK::ElasticLoadBalancingv2::SSLPolicy::TLS12_EXT,
},
],
},
],
target_groups: [
{
container_port: 80,
listener: "listener",
},
{
container_port: 90,
path_pattern: "a/b/c",
priority: 10,
listener: "listener",
},
{
container_port: 443,
listener: "listener2",
},
{
container_port: 80,
path_pattern: "a/b/c",
priority: 10,
listener: "listener2",
},
],
})
require 'aws-cdk-lib'
vpc = AWSCDK::EC2::VPC.new(self, "Vpc", {max_azs: 1})
load_balanced_fargate_service = AWSCDK::ECSPatterns::ApplicationMultipleTargetGroupsFargateService.new(self, "myService", {
cluster: AWSCDK::ECS::Cluster.new(self, "EcsCluster", {vpc: vpc}),
memory_limit_mi_b: 256,
task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
},
enable_execute_command: true,
load_balancers: [
{
name: "lb",
idle_timeout: AWSCDK::Duration.seconds(400),
domain_name: "api.example.com",
domain_zone: AWSCDK::Route53::PublicHostedZone.new(self, "HostedZone", {zone_name: "example.com"}),
listeners: [
{
name: "listener",
protocol: AWSCDK::ElasticLoadBalancingv2::ApplicationProtocol::HTTPS,
certificate: AWSCDK::CertificateManager::Certificate.from_certificate_arn(self, "Cert", "helloworld"),
ssl_policy: AWSCDK::ElasticLoadBalancingv2::SSLPolicy::TLS12_EXT,
},
],
},
{
name: "lb2",
idle_timeout: AWSCDK::Duration.seconds(120),
domain_name: "frontend.com",
domain_zone: AWSCDK::Route53::PublicHostedZone.new(self, "HostedZone", {zone_name: "frontend.com"}),
listeners: [
{
name: "listener2",
protocol: AWSCDK::ElasticLoadBalancingv2::ApplicationProtocol::HTTPS,
certificate: AWSCDK::CertificateManager::Certificate.from_certificate_arn(self, "Cert2", "helloworld"),
ssl_policy: AWSCDK::ElasticLoadBalancingv2::SSLPolicy::TLS12_EXT,
},
],
},
],
target_groups: [
{
container_port: 80,
listener: "listener",
},
{
container_port: 90,
path_pattern: "a/b/c",
priority: 10,
listener: "listener",
},
{
container_port: 443,
listener: "listener2",
},
{
container_port: 80,
path_pattern: "a/b/c",
priority: 10,
listener: "listener2",
},
],
})
load_balanced_fargate_service.target_groups[0].configure_health_check({
port: "8050",
protocol: AWSCDK::ElasticLoadBalancingv2::Protocol::HTTP,
healthy_threshold_count: 2,
unhealthy_threshold_count: 2,
timeout: AWSCDK::Duration.seconds(10),
interval: AWSCDK::Duration.seconds(30),
healthy_http_codes: "200",
})
load_balanced_fargate_service.target_groups[1].configure_health_check({
port: "8050",
protocol: AWSCDK::ElasticLoadBalancingv2::Protocol::HTTP,
healthy_threshold_count: 2,
unhealthy_threshold_count: 2,
timeout: AWSCDK::Duration.seconds(10),
interval: AWSCDK::Duration.seconds(30),
healthy_http_codes: "200",
})
cluster = nil # AWSCDK::ECS::Cluster
application_load_balanced_fargate_service = AWSCDK::ECSPatterns::ApplicationLoadBalancedFargateService.new(self, "Service", {
cluster: cluster,
memory_limit_mi_b: 512,
task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
},
min_healthy_percent: 100,
runtime_platform: {
cpu_architecture: AWSCDK::ECS::CpuArchitecture.ARM64,
operating_system_family: AWSCDK::ECS::OperatingSystemFamily.LINUX,
},
})
cluster = nil # AWSCDK::ECS::Cluster
scheduled_fargate_task = AWSCDK::ECSPatterns::ScheduledFargateTask.new(self, "ScheduledFargateTask", {
cluster: cluster,
scheduled_fargate_task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
container_name: "customContainerName",
memory_limit_mi_b: 512,
},
schedule: AWSCDK::ApplicationAutoScaling::Schedule.expression("rate(1 minute)"),
platform_version: AWSCDK::ECS::FargatePlatformVersion::LATEST,
})
cluster = nil # AWSCDK::ECS::Cluster
ecs_scheduled_task = AWSCDK::ECSPatterns::ScheduledEC2Task.new(self, "ScheduledTask", {
cluster: cluster,
scheduled_ec2_task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
container_name: "customContainerName",
memory_limit_mi_b: 256,
environment: {name: "TRIGGER", value: "CloudWatch Events"},
},
schedule: AWSCDK::ApplicationAutoScaling::Schedule.expression("rate(1 minute)"),
enabled: true,
rule_name: "sample-scheduled-task-rule",
})
cluster = nil # AWSCDK::ECS::Cluster
scheduled_fargate_task = AWSCDK::ECSPatterns::ScheduledFargateTask.new(self, "ScheduledFargateTask", {
cluster: cluster,
scheduled_fargate_task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
memory_limit_mi_b: 512,
},
schedule: AWSCDK::ApplicationAutoScaling::Schedule.expression("rate(1 minute)"),
platform_version: AWSCDK::ECS::FargatePlatformVersion::VERSION1_4,
})
vpc = AWSCDK::EC2::VPC.new(self, "Vpc", {max_azs: 1})
cluster = AWSCDK::ECS::Cluster.new(self, "EcsCluster", {vpc: vpc})
security_group = AWSCDK::EC2::SecurityGroup.new(self, "SG", {vpc: vpc})
scheduled_fargate_task = AWSCDK::ECSPatterns::ScheduledFargateTask.new(self, "ScheduledFargateTask", {
cluster: cluster,
scheduled_fargate_task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
memory_limit_mi_b: 512,
},
schedule: AWSCDK::ApplicationAutoScaling::Schedule.expression("rate(1 minute)"),
security_groups: [security_group],
})
The following is an example of deploying an application along with a metrics sidecar container that utilizes docker_labels for discovery:
cluster = nil # AWSCDK::ECS::Cluster
vpc = nil # AWSCDK::EC2::VPC
service = AWSCDK::ECSPatterns::ApplicationLoadBalancedFargateService.new(self, "Service", {
cluster: cluster,
vpc: vpc,
desired_count: 1,
min_healthy_percent: 100,
task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
docker_labels: {
"application.label.one" => "first_label",
"application.label.two" => "second_label",
},
},
})
service.task_definition.add_container("Sidecar", {
image: AWSCDK::ECS::ContainerImage.from_registry("example/metrics-sidecar"),
})
cluster = nil # AWSCDK::ECS::Cluster
load_balanced_fargate_service = AWSCDK::ECSPatterns::ApplicationLoadBalancedFargateService.new(self, "Service", {
cluster: cluster,
memory_limit_mi_b: 1024,
desired_count: 1,
cpu: 512,
task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
},
min_healthy_percent: 100,
task_subnets: {
subnets: [AWSCDK::EC2::Subnet.from_subnet_id(self, "subnet", "VpcISOLATEDSubnet1Subnet80F07FA0")],
},
load_balancer_name: "application-lb-name",
})
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 enable_execute_command 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 ScheduledTasks.
Read more about ECS Exec in the ECS Developer Guide.
Example:
cluster = nil # AWSCDK::ECS::Cluster
load_balanced_fargate_service = AWSCDK::ECSPatterns::ApplicationLoadBalancedFargateService.new(self, "Service", {
cluster: cluster,
memory_limit_mi_b: 1024,
desired_count: 1,
cpu: 512,
task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
},
min_healthy_percent: 100,
enable_execute_command: 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.
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 propagate_tags to ecs.PropagatedTagSource.TASK_DEFINITION as
shown below:
require 'aws-cdk-lib'
vpc = AWSCDK::EC2::VPC.new(self, "Vpc", {max_azs: 1})
cluster = AWSCDK::ECS::Cluster.new(self, "EcsCluster", {vpc: vpc})
task_definition = AWSCDK::ECS::FargateTaskDefinition.new(self, "TaskDef", {
memory_limit_mi_b: 512,
cpu: 256,
})
task_definition.add_container("WebContainer", {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
})
AWSCDK::Tags.of(task_definition).add("my-tag", "my-tag-value")
scheduled_fargate_task = AWSCDK::ECSPatterns::ScheduledFargateTask.new(self, "ScheduledFargateTask", {
cluster: cluster,
task_definition: task_definition,
schedule: AWSCDK::ApplicationAutoScaling::Schedule.expression("rate(1 minute)"),
propagate_tags: AWSCDK::ECS::PropagatedTagSource::TASK_DEFINITION,
})
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 propagate_tags attribute.
vpc = AWSCDK::EC2::VPC.new(self, "Vpc", {max_azs: 1})
cluster = AWSCDK::ECS::Cluster.new(self, "EcsCluster", {vpc: vpc})
scheduled_fargate_task = AWSCDK::ECSPatterns::ScheduledFargateTask.new(self, "ScheduledFargateTask", {
cluster: cluster,
scheduled_fargate_task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
memory_limit_mi_b: 512,
},
schedule: AWSCDK::ApplicationAutoScaling::Schedule.expression("rate(1 minute)"),
tags: [
{
key: "my-tag",
value: "my-tag-value",
},
],
})
You can pass a custom ephemeral storage (21GiB - 200GiB) to ECS Fargate tasks on Fargate Platform Version 1.4.0 or later.
vpc = AWSCDK::EC2::VPC.new(self, "Vpc", {max_azs: 2, restrict_default_security_group: false})
cluster = AWSCDK::ECS::Cluster.new(self, "FargateCluster", {vpc: vpc})
application_load_balanced_fargate_service = AWSCDK::ECSPatterns::ApplicationLoadBalancedFargateService.new(self, "ALBFargateServiceWithCustomEphemeralStorage", {
cluster: cluster,
memory_limit_mi_b: 1024,
cpu: 512,
ephemeral_storage_gi_b: 21,
task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
},
min_healthy_percent: 100,
})
network_load_balanced_fargate_service = AWSCDK::ECSPatterns::NetworkLoadBalancedFargateService.new(self, "NLBFargateServiceWithCustomEphemeralStorage", {
cluster: cluster,
memory_limit_mi_b: 1024,
cpu: 512,
ephemeral_storage_gi_b: 200,
task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
},
min_healthy_percent: 100,
})
vpc = nil # AWSCDK::EC2::VPC
queue_processing_fargate_service = AWSCDK::ECSPatterns::QueueProcessingFargateService.new(self, "Service", {
vpc: vpc,
memory_limit_mi_b: 512,
image: AWSCDK::ECS::ContainerImage.from_registry("test"),
min_healthy_percent: 100,
health_check_grace_period: AWSCDK::Duration.seconds(120),
})
vpc = nil # AWSCDK::EC2::VPC
security_group = nil # AWSCDK::EC2::SecurityGroup
queue_processing_fargate_service = AWSCDK::ECSPatterns::NetworkLoadBalancedFargateService.new(self, "Service", {
vpc: vpc,
memory_limit_mi_b: 512,
task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
},
min_healthy_percent: 100,
security_groups: [security_group],
})
To set up TLS listener in Network Load Balancer, you need to pass extactly one ACM certificate into the option listener_certificate. The listener port and the target group port will also become 443 by default. You can override the listener's port with listener_port and the target group's port with taskImageOptions.containerPort.
require 'aws-cdk-lib'
certificate = AWSCDK::CertificateManager::Certificate.from_certificate_arn(self, "Cert", "arn:aws:acm:us-east-1:123456:certificate/abcdefg")
load_balanced_fargate_service = AWSCDK::ECSPatterns::NetworkLoadBalancedFargateService.new(self, "Service", {
# The default value of listenerPort is 443 if you pass in listenerCertificate
# It is configured to port 4443 here
listener_port: 4443,
listener_certificate: certificate,
task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
# The default value of containerPort is 443 if you pass in listenerCertificate
# It is configured to port 8443 here
container_port: 8443,
},
})
require 'aws-cdk-lib'
cluster = nil # AWSCDK::ECS::Cluster
certificate = AWSCDK::CertificateManager::Certificate.from_certificate_arn(self, "Cert", "arn:aws:acm:us-east-1:123456:certificate/abcdefg")
load_balanced_ecs_service = AWSCDK::ECSPatterns::NetworkLoadBalancedEC2Service.new(self, "Service", {
cluster: cluster,
memory_limit_mi_b: 1024,
# The default value of listenerPort is 443 if you pass in listenerCertificate
# It is configured to port 4443 here
listener_port: 4443,
listener_certificate: certificate,
task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("test"),
# The default value of containerPort is 443 if you pass in listenerCertificate
# It is configured to port 8443 here
container_port: 8443,
environment: {
TEST_ENVIRONMENT_VARIABLE1: "test environment variable 1 value",
TEST_ENVIRONMENT_VARIABLE2: "test environment variable 2 value",
},
},
desired_count: 2,
})
You can use dualstack IP address type for Application Load Balancer and Network Load Balancer.
To use dualstack IP address type, you must have associated IPv6 CIDR blocks with the VPC and subnets and set the ip_address_type to IpAddressType.DUAL_STACK when creating the load balancer.
You can use dualstack Application Load Balancer for Fargate and EC2 services.
require 'aws-cdk-lib'
# The VPC and subnet must have associated IPv6 CIDR blocks.
vpc = AWSCDK::EC2::VPC.new(self, "Vpc", {
ip_protocol: AWSCDK::EC2::IPProtocol::DUAL_STACK,
})
cluster = AWSCDK::ECS::Cluster.new(self, "EcsCluster", {vpc: vpc})
service = AWSCDK::ECSPatterns::ApplicationLoadBalancedFargateService.new(self, "myService", {
cluster: cluster,
task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
},
min_healthy_percent: 100,
ip_address_type: AWSCDK::ElasticLoadBalancingv2::IPAddressType::DUAL_STACK,
})
application_load_balanced_ec2_service = AWSCDK::ECSPatterns::ApplicationLoadBalancedEC2Service.new(self, "myService", {
cluster: cluster,
task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
},
min_healthy_percent: 100,
ip_address_type: AWSCDK::ElasticLoadBalancingv2::IPAddressType::DUAL_STACK,
})
You can use dualstack Network Load Balancer for Fargate and EC2 services.
require 'aws-cdk-lib'
# The VPC and subnet must have associated IPv6 CIDR blocks.
vpc = AWSCDK::EC2::VPC.new(self, "Vpc", {
ip_protocol: AWSCDK::EC2::IPProtocol::DUAL_STACK,
})
cluster = AWSCDK::ECS::Cluster.new(self, "EcsCluster", {vpc: vpc})
network_loadbalanced_fargate_service = AWSCDK::ECSPatterns::NetworkLoadBalancedFargateService.new(self, "NlbFargateService", {
cluster: cluster,
task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
},
min_healthy_percent: 100,
ip_address_type: AWSCDK::ElasticLoadBalancingv2::IPAddressType::DUAL_STACK,
})
network_loadbalanced_ec2_service = AWSCDK::ECSPatterns::NetworkLoadBalancedEC2Service.new(self, "NlbEc2Service", {
cluster: cluster,
task_image_options: {
image: AWSCDK::ECS::ContainerImage.from_registry("amazon/amazon-ecs-sample"),
},
min_healthy_percent: 100,
ip_address_type: AWSCDK::ElasticLoadBalancingv2::IPAddressType::DUAL_STACK,
})