AWS::ECS::Service - AWS CloudFormation (original) (raw)

The AWS::ECS::Service resource creates an Amazon Elastic Container Service (Amazon ECS) service that runs and maintains the requested number of tasks and associated load balancers.

Important

The stack update fails if you change any properties that require replacement and at least one Amazon ECS Service Connect ServiceConnectConfiguration property is configured. This is because AWS CloudFormation creates the replacement service first, but each ServiceConnectService must have a name that is unique in the namespace.

Note

Starting April 15, 2023, AWS; will not onboard new customers to Amazon Elastic Inference (EI), and will help current customers migrate their workloads to options that offer better price and performance. After April 15, 2023, new customers will not be able to launch instances with Amazon EI accelerators in Amazon SageMaker, Amazon ECS, or Amazon EC2. However, customers who have used Amazon EI at least once during the past 30-day period are considered current customers and will be able to continue using the service.

Syntax

To declare this entity in your AWS CloudFormation template, use the following syntax:

JSON

{
  "Type" : "AWS::ECS::Service",
  "Properties" : {
      "AvailabilityZoneRebalancing" : String,
      "CapacityProviderStrategy" : [ CapacityProviderStrategyItem, ... ],
      "Cluster" : String,
      "DeploymentConfiguration" : DeploymentConfiguration,
      "DeploymentController" : DeploymentController,
      "DesiredCount" : Integer,
      "EnableECSManagedTags" : Boolean,
      "EnableExecuteCommand" : Boolean,
      "HealthCheckGracePeriodSeconds" : Integer,
      "LaunchType" : String,
      "LoadBalancers" : [ LoadBalancer, ... ],
      "NetworkConfiguration" : NetworkConfiguration,
      "PlacementConstraints" : [ PlacementConstraint, ... ],
      "PlacementStrategies" : [ PlacementStrategy, ... ],
      "PlatformVersion" : String,
      "PropagateTags" : String,
      "Role" : String,
      "SchedulingStrategy" : String,
      "ServiceConnectConfiguration" : ServiceConnectConfiguration,
      "ServiceName" : String,
      "ServiceRegistries" : [ ServiceRegistry, ... ],
      "Tags" : [ Tag, ... ],
      "TaskDefinition" : String,
      "VolumeConfigurations" : [ ServiceVolumeConfiguration, ... ],
      "VpcLatticeConfigurations" : [ VpcLatticeConfiguration, ... ]
    }
}

Properties

AvailabilityZoneRebalancing

Indicates whether to use Availability Zone rebalancing for the service.

For more information, see Balancing an Amazon ECS service across Availability Zones in the _Amazon Elastic Container Service Developer Guide .

Required: No

Type: String

Allowed values: ENABLED | DISABLED

Update requires: No interruption

CapacityProviderStrategy

The capacity provider strategy to use for the service.

If a capacityProviderStrategy is specified, the launchType parameter must be omitted. If no capacityProviderStrategy orlaunchType is specified, thedefaultCapacityProviderStrategy for the cluster is used.

A capacity provider strategy can contain a maximum of 20 capacity providers.

Important

To remove this property from your service resource, specify an empty CapacityProviderStrategyItem array.

Required: No

Type: Array of CapacityProviderStrategyItem

Update requires: No interruption

Cluster

The short name or full Amazon Resource Name (ARN) of the cluster that you run your service on. If you do not specify a cluster, the default cluster is assumed.

Required: No

Type: String

Update requires: Replacement

DeploymentConfiguration

Optional deployment parameters that control how many tasks run during the deployment and the ordering of stopping and starting tasks.

Required: No

Type: DeploymentConfiguration

Update requires: No interruption

DeploymentController

The deployment controller to use for the service. If no deployment controller is specified, the default value of ECS is used.

Required: No

Type: DeploymentController

Update requires: Some interruptions

DesiredCount

The number of instantiations of the specified task definition to place and keep running in your service.

For new services, if a desired count is not specified, a default value of 1 is used. When using the DAEMON scheduling strategy, the desired count is not required.

For existing services, if a desired count is not specified, it is omitted from the operation.

Required: Conditional

Type: Integer

Update requires: No interruption

EnableECSManagedTags

Specifies whether to turn on Amazon ECS managed tags for the tasks within the service. For more information, see Tagging your Amazon ECS resources in the Amazon Elastic Container Service Developer Guide.

When you use Amazon ECS managed tags, you need to set the propagateTags request parameter.

Required: No

Type: Boolean

Update requires: No interruption

EnableExecuteCommand

Determines whether the execute command functionality is turned on for the service. Iftrue, the execute command functionality is turned on for all containers in tasks as part of the service.

Required: No

Type: Boolean

Update requires: No interruption

HealthCheckGracePeriodSeconds

The period of time, in seconds, that the Amazon ECS service scheduler ignores unhealthy Elastic Load Balancing, VPC Lattice, and container health checks after a task has first started. If you don't specify a health check grace period value, the default value of 0 is used. If you don't use any of the health checks, thenhealthCheckGracePeriodSeconds is unused.

If your service's tasks take a while to start and respond to health checks, you can specify a health check grace period of up to 2,147,483,647 seconds (about 69 years). During that time, the Amazon ECS service scheduler ignores health check status. This grace period can prevent the service scheduler from marking tasks as unhealthy and stopping them before they have time to come up.

Required: No

Type: Integer

Update requires: No interruption

LaunchType

The launch type on which to run your service. For more information, see Amazon ECS Launch Types in the Amazon Elastic Container Service Developer Guide.

Required: No

Type: String

Allowed values: EC2 | FARGATE | EXTERNAL

Update requires: Replacement

LoadBalancers

A list of load balancer objects to associate with the service. If you specify theRole property, LoadBalancers must be specified as well. For information about the number of load balancers that you can specify per service, see Service Load Balancing in the Amazon Elastic Container Service Developer Guide.

Important

To remove this property from your service resource, specify an empty LoadBalancer array.

Required: No

Type: Array of LoadBalancer

Update requires: No interruption

NetworkConfiguration

The network configuration for the service. This parameter is required for task definitions that use the awsvpc network mode to receive their own elastic network interface, and it is not supported for other network modes. For more information, see Task Networking in the Amazon Elastic Container Service Developer Guide.

Required: Conditional

Type: NetworkConfiguration

Update requires: No interruption

PlacementConstraints

An array of placement constraint objects to use for tasks in your service. You can specify a maximum of 10 constraints for each task. This limit includes constraints in the task definition and those specified at runtime.

Important

To remove this property from your service resource, specify an empty PlacementConstraint array.

Required: No

Type: Array of PlacementConstraint

Update requires: No interruption

PlacementStrategies

The placement strategy objects to use for tasks in your service. You can specify a maximum of 5 strategy rules for each service.

Important

To remove this property from your service resource, specify an empty PlacementStrategy array.

Required: No

Type: Array of PlacementStrategy

Update requires: No interruption

PlatformVersion

The platform version that your tasks in the service are running on. A platform version is specified only for tasks using the Fargate launch type. If one isn't specified, the LATEST platform version is used. For more information, seeAWS Fargate platform versions in the Amazon Elastic Container Service Developer Guide.

Required: No

Type: String

Update requires: No interruption

PropagateTags

Specifies whether to propagate the tags from the task definition to the task. If no value is specified, the tags aren't propagated. Tags can only be propagated to the task during task creation. To add tags to a task after task creation, use the TagResource API action.

You must set this to a value other than NONE when you use Cost Explorer. For more information, see Amazon ECS usage reports in the Amazon Elastic Container Service Developer Guide.

The default is NONE.

Required: No

Type: String

Allowed values: SERVICE | TASK_DEFINITION

Update requires: No interruption

Role

The name or full Amazon Resource Name (ARN) of the IAM role that allows Amazon ECS to make calls to your load balancer on your behalf. This parameter is only permitted if you are using a load balancer with your service and your task definition doesn't use the awsvpc network mode. If you specify the role parameter, you must also specify a load balancer object with the loadBalancers parameter.

Important

If your account has already created the Amazon ECS service-linked role, that role is used for your service unless you specify a role here. The service-linked role is required if your task definition uses the awsvpc network mode or if the service is configured to use service discovery, an external deployment controller, multiple target groups, or Elastic Inference accelerators in which case you don't specify a role here. For more information, see Using service-linked roles for Amazon ECS in the Amazon Elastic Container Service Developer Guide.

If your specified role has a path other than /, then you must either specify the full role ARN (this is recommended) or prefix the role name with the path. For example, if a role with the name bar has a path of /foo/ then you would specify /foo/bar as the role name. For more information, seeFriendly names and paths in the IAM User Guide.

Required: No

Type: String

Update requires: Replacement

SchedulingStrategy

The scheduling strategy to use for the service. For more information, see Services.

There are two service scheduler strategies available:

Note

Tasks using the Fargate launch type or theCODE_DEPLOY or EXTERNAL deployment controller types don't support the DAEMON scheduling strategy.

Required: No

Type: String

Allowed values: DAEMON | REPLICA

Update requires: Replacement

ServiceConnectConfiguration

The configuration for this service to discover and connect to services, and be discovered by, and connected from, other services within a namespace.

Tasks that run in a namespace can use short names to connect to services in the namespace. Tasks can connect to services across all of the clusters in the namespace. Tasks connect through a managed proxy container that collects logs and metrics for increased visibility. Only the tasks that Amazon ECS services create are supported with Service Connect. For more information, see Service Connect in the Amazon Elastic Container Service Developer Guide.

Required: No

Type: ServiceConnectConfiguration

Update requires: No interruption

ServiceName

The name of your service. Up to 255 letters (uppercase and lowercase), numbers, underscores, and hyphens are allowed. Service names must be unique within a cluster, but you can have similarly named services in multiple clusters within a Region or across multiple Regions.

Important

The stack update fails if you change any properties that require replacement and theServiceName is configured. This is because AWS CloudFormation creates the replacement service first, but each ServiceName must be unique in the cluster.

Required: No

Type: String

Update requires: Replacement

ServiceRegistries

The details of the service discovery registry to associate with this service. For more information, see Service discovery.

Note

Each service may be associated with one service registry. Multiple service registries for each service isn't supported.

Important

To remove this property from your service resource, specify an empty ServiceRegistry array.

Required: No

Type: Array of ServiceRegistry

Update requires: No interruption

Tags

The metadata that you apply to the service to help you categorize and organize them. Each tag consists of a key and an optional value, both of which you define. When a service is deleted, the tags are deleted as well.

The following basic restrictions apply to tags:

Required: No

Type: Array of Tag

Minimum: 0

Maximum: 50

Update requires: No interruption

TaskDefinition

The family and revision (family:revision) or full ARN of the task definition to run in your service. If a revision isn't specified, the latest ACTIVE revision is used.

A task definition must be specified if the service uses either the ECS orCODE_DEPLOY deployment controllers.

For more information about deployment types, see Amazon ECS deployment types.

Required: No

Type: String

Update requires: No interruption

VolumeConfigurations

The configuration for a volume specified in the task definition as a volume that is configured at launch time. Currently, the only supported volume type is an Amazon EBS volume.

Important

To remove this property from your service resource, specify an empty ServiceVolumeConfiguration array.

Required: No

Type: Array of ServiceVolumeConfiguration

Update requires: No interruption

VpcLatticeConfigurations

The VPC Lattice configuration for the service being created.

Required: No

Type: Array of VpcLatticeConfiguration

Update requires: No interruption

Return values

Ref

When you pass the logical ID of this resource to the intrinsic Ref function, Ref returns the Amazon Resource Name (ARN).

In the following example, the Ref function returns the ARN of theMyECSService service, such asarn:aws:ecs:us-west-2:123456789012:service/sample-webapp.

{ "Ref": "MyECSService" }

For more information about using the Ref function, see Ref.

Fn::GetAtt

The Fn::GetAtt intrinsic function returns a value for a specified attribute of this type. The following are the available attributes and sample return values.

For more information about using the Fn::GetAtt intrinsic function, see Fn::GetAtt.

Name

The name of the Amazon ECS service, such as sample-webapp.

ServiceArn

Not currently supported in AWS CloudFormation.

Examples

Create a service that uses a task definition

The following example template creates a service, a cluster, and a task definition. The cluster contains the service. The service — with aDesiredCount of 1 — uses the task definition defined in the template. Replace the ExecutionRoleArn, SecurityGroups, andSubnets with your own information.

JSON

{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Resources": {
        "ECSCluster": {
            "Type": "AWS::ECS::Cluster",
            "Properties": {
                "ClusterName": "CFNCluster"
            }
        },
        "ECSTaskDefinition": {
            "Type": "AWS::ECS::TaskDefinition",
            "Properties": {
                "ContainerDefinitions": [
                    {
                        "Command": [
                            "/bin/sh -c \"echo '<html> <head> <title>Amazon ECS Sample App</title> <style>body {margin-top: 40px; background-color: #333;} </style> </head><body> <div style=color:white;text-align:center> <h1>Amazon ECS Sample App</h1> <h2>Congratulations!</h2> <p>Your application is now running on a container in Amazon ECS.</p> </div></body></html>' >  /usr/local/apache2/htdocs/index.html && httpd-foreground\""
                        ],
                        "EntryPoint": [
                            "sh",
                            "-c"
                        ],
                        "Essential": true,
                        "Image": "public.ecr.aws/docker/library/httpd:2.4",
                        "LogConfiguration": {
                            "LogDriver": "awslogs",
                            "Options": {
                                "awslogs-group": "/ecs/fargate-task-definition",
                                "awslogs-region": "us-east-1",
                                "awslogs-stream-prefix": "ecs"
                            }
                        },
                        "Name": "sample-fargate-app",
                        "PortMappings": [
                            {
                                "ContainerPort": 80,
                                "HostPort": 80,
                                "Protocol": "tcp"
                            }
                        ]
                    }
                ],
                "Cpu": 256,
                "ExecutionRoleArn": "arn:aws:iam::111122223333:role/ecsTaskExecutionRole",
                "Family": "task-definition-cfn",
                "Memory": 512,
                "NetworkMode": "awsvpc",
                "RequiresCompatibilities": [
                    "FARGATE"
                ],
                "RuntimePlatform": {
                    "OperatingSystemFamily": "LINUX"
                }
            }
        },
        "ECSService": {
            "Type": "AWS::ECS::Service",
            "Properties": {
                "ServiceName": "cfn-service",
                "Cluster": {
                    "Ref": "ECSCluster"
                },
                "DesiredCount": 1,
                "LaunchType": "FARGATE",
                "NetworkConfiguration": {
                    "AwsvpcConfiguration": {
                        "AssignPublicIp": "ENABLED",
                        "SecurityGroups": [
                            "sg-abcdef01234567890"
                        ],
                        "Subnets": [
                            "subnet-021345abcdef67890"
                        ]
                    }
                },
                "TaskDefinition": {
                    "Ref": "ECSTaskDefinition"
                }
            }
        }
    }
}

YAML

AWSTemplateFormatVersion: 2010-09-09
Resources:
  ECSCluster:
    Type: 'AWS::ECS::Cluster'
    Properties:
      ClusterName: CFNCluster
  ECSTaskDefinition:
    Type: 'AWS::ECS::TaskDefinition'
    Properties:
      ContainerDefinitions:
        - Command:
            - >-
              /bin/sh -c "echo '<html> <head> <title>Amazon ECS Sample
              App</title> <style>body {margin-top: 40px; background-color:
              #333;} </style> </head><body> <div
              style=color:white;text-align:center> <h1>Amazon ECS Sample
              App</h1> <h2>Congratulations!</h2> <p>Your application is now
              running on a container in Amazon ECS.</p> </div></body></html>' > 
              /usr/local/apache2/htdocs/index.html && httpd-foreground"
          EntryPoint:
            - sh
            - '-c'
          Essential: true
          Image: 'public.ecr.aws/docker/library/httpd:2.4'
          LogConfiguration:
            LogDriver: awslogs
            Options:
              awslogs-group: /ecs/fargate-task-definition
              awslogs-region: us-east-1
              awslogs-stream-prefix: ecs
          Name: sample-fargate-app
          PortMappings:
            - ContainerPort: 80
              HostPort: 80
              Protocol: tcp
      Cpu: 256
      ExecutionRoleArn: 'arn:aws:iam::111122223333:role/ecsTaskExecutionRole'
      Family: task-definition-cfn
      Memory: 512
      NetworkMode: awsvpc
      RequiresCompatibilities:
        - FARGATE
      RuntimePlatform:
        OperatingSystemFamily: LINUX
  ECSService:
    Type: 'AWS::ECS::Service'
    Properties:
      ServiceName: cfn-service
      Cluster: !Ref ECSCluster
      DesiredCount: 1
      LaunchType: FARGATE
      NetworkConfiguration:
        AwsvpcConfiguration:
          AssignPublicIp: ENABLED
          SecurityGroups:
            - sg-abcdef01234567890
          Subnets:
            - subnet-021345abcdef67890
      TaskDefinition: !Ref ECSTaskDefinition

Create a service with a volume configuration

The following example template creates a service that utilizes a pre-existing task that defers volume configuration to service creation. This example template provides volume configuration that Amazon ECS uses to create and attach an Amazon EBS volume to each task in the service. For more information about defering volume configuration and using Amazon EBS volumes with Amazon ECS, see Use Amazon EBS volumes with Amazon ECS in the Amazon ECS Developer Guide. Replace SubnetIDs, SecurityGroupIDs, TaskDefinition, and ManagedEBSVolume with your own information.

JSON

{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Description": "The template used to create an ECS Service that includes a volume configuration.",
    "Parameters": {
      "ECSClusterName": {
        "Type": "String",
        "Default": "volume-config-cluster"
      },
      "SecurityGroupIDs": {
        "Type": "CommaDelimitedList",
        "Default": "sg-1234567890abcdef0"
      },
      "SubnetIDs": {
        "Type": "CommaDelimitedList",
        "Default": "subnet-021345abcdef67890,subnet-abcdef01234567890"
      }
    },
    "Resources": {
      "ECSService": {
        "Type": "AWS::ECS::Service",
        "Properties": {
          "Cluster": "endpoint",
          "TaskDefinition": "arn:aws:ecs:us-east-1:111122223333:task-definition/ebs-task-attach-task-def-test:11",
          "LaunchType": "FARGATE",
          "ServiceName": "ebs",
          "SchedulingStrategy": "REPLICA",
          "DesiredCount": 1,
          "NetworkConfiguration": {
            "AwsvpcConfiguration": {
              "AssignPublicIp": "ENABLED",
              "SecurityGroups": {
                "Ref": "SecurityGroupIDs"
              },
              "Subnets": {
                "Ref": "SubnetIDs"
              }
            }
          },
          "PlatformVersion": "LATEST",
          "DeploymentConfiguration": {
            "MaximumPercent": 200,
            "MinimumHealthyPercent": 100,
            "DeploymentCircuitBreaker": {
              "Enable": true,
              "Rollback": true
            }
          },
          "DeploymentController": {
            "Type": "ECS"
          },
          "Tags": [],
          "EnableECSManagedTags": true,
          "VolumeConfigurations": [
            {
              "Name": "ebs-volume",
              "ManagedEBSVolume": {
                "RoleArn": "arn:aws:iam::111122223333:role/ecsInfrastructureRole",
                "VolumeType": "gp3",
                "Iops": "3000",
                "Throughput": "125",
                "SizeInGiB": "10",
                "FilesystemType": "xfs",
                "TagSpecifications": [
                  {
                    "ResourceType": "volume",
                    "PropagateTags": "TASK_DEFINITION"
                  }
                ]
              }
            }
          ]
        }
      }
    },
    "Outputs": {
      "ClusterName": {
        "Description": "The cluster used to create the service.",
        "Value": {
          "Ref": "ECSClusterName"
        }
      },
      "ECSService": {
        "Description": "The created service.",
        "Value": {
          "Ref": "ECSService"
        }
      }
    }
  }

YAML

AWSTemplateFormatVersion: 2010-09-09
Description: The template used to create an ECS Service that includes a volume configuration.
Parameters:
  ECSClusterName:
    Type: String
    Default: volume-config-cluster
  SecurityGroupIDs:
    Type: CommaDelimitedList
    Default: sg-1234567890abcdef0
  SubnetIDs:
    Type: CommaDelimitedList
    Default: subnet-021345abcdef67890,subnet-abcdef01234567890
Resources:
  ECSService:
    Type: AWS::ECS::Service
    Properties:
      Cluster: endpoint
      TaskDefinition: arn:aws:ecs:us-east-1:111122223333:task-definition/ebs-task-attach-task-def-test:11
      LaunchType: FARGATE
      ServiceName: ebs
      SchedulingStrategy: REPLICA
      DesiredCount: 1
      NetworkConfiguration:
        AwsvpcConfiguration:
          AssignPublicIp: ENABLED
          SecurityGroups:
            Ref: SecurityGroupIDs
          Subnets:
            Ref: SubnetIDs
      PlatformVersion: LATEST
      DeploymentConfiguration:
        MaximumPercent: 200
        MinimumHealthyPercent: 100
        DeploymentCircuitBreaker:
          Enable: true
          Rollback: true
      DeploymentController:
        Type: ECS
      Tags: []
      EnableECSManagedTags: true
      VolumeConfigurations:
        - Name: ebs-volume
          ManagedEBSVolume:
            RoleArn: arn:aws:iam::111122223333:role/ecsInfrastructureRole
            VolumeType: gp3
            Iops: "3000"
            Throughput: "125"
            SizeInGiB: "10"
            FilesystemType: xfs
            TagSpecifications:
              - ResourceType: volume
                PropagateTags: TASK_DEFINITION
Outputs:
  ClusterName:
    Description: The cluster used to create the service.
    Value:
      Ref: ECSClusterName
  ECSService:
    Description: The created service.
    Value:
      Ref: ECSService  

Associate an Application Load Balancer with a service

The following example associates an Application Load Balancer with an Amazon ECS service by referencing an AWS::ElasticLoadBalancingV2::TargetGroup resource. Replace the SecurityGroupIDs, SubnetIDs,VpcID, Cluster, and TaskDefinition with your own information. For more information about using Application Load Balancers with Amazon ECS, see Use an Application Load Balancer for Amazon ECS in the Amazon ECS Developer Guide.

Note

The Amazon ECS service requires an explicit dependency on the Application Load Balancer listener rule and the Application Load Balancer listener. This prevents the service from starting before the listener is ready.

JSON

{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Description": "The template used to create an ECS Service associated with an Application Load Balancer.",
    "Parameters": {
      "SecurityGroupIDs": {
        "Type": "CommaDelimitedList",
        "Default": "sg-1234567890abcdef0,sg-021345abcdef67890"
      },
      "SubnetIDs": {
        "Type": "CommaDelimitedList",
        "Default": "subnet-abcdef01234567890,subnet-fedcba01234567098,subnet-2135647890abcdef0"
      },
      "VpcID": {
        "Type": "String",
        "Default": "vpc-3214789650abcdef0"
      }
    },
    "Resources": {
        "ECSCluster": {
            "Type": "AWS::ECS::Cluster",
            "Properties": {
                "ClusterName": "ALBCluster"
            }
        },
      "ECSService": {
        "Type": "AWS::ECS::Service",
        "Properties": {
          "Cluster": {"Ref":"ECSCluster"},
          "TaskDefinition": "arn:aws:ecs:us-east-1:111122223333:task-definition/first-run-task:7",
          "LaunchType": "FARGATE",
          "ServiceName": "alb",
          "SchedulingStrategy": "REPLICA",
          "DesiredCount": 3,
          "LoadBalancers": [
            {
              "ContainerName": "first-run-task",
              "ContainerPort": 80,
              "LoadBalancerName": {
                "Ref": "AWS::NoValue"
              },
              "TargetGroupArn": {
                "Ref": "TargetGroup"
              }
            }
          ],
          "HealthCheckGracePeriodSeconds": "20",
          "NetworkConfiguration": {
            "AwsvpcConfiguration": {
              "AssignPublicIp": "ENABLED",
              "SecurityGroups": {
                "Ref": "SecurityGroupIDs"
              },
              "Subnets": {
                "Ref": "SubnetIDs"
              }
            }
          },
          "PlatformVersion": "LATEST",
          "DeploymentConfiguration": {
            "MaximumPercent": 200,
            "MinimumHealthyPercent": 100,
            "DeploymentCircuitBreaker": {
              "Enable": true,
              "Rollback": true
            }
          },
          "DeploymentController": {
            "Type": "ECS"
          },
          "ServiceConnectConfiguration": {
            "Enabled": false
          },
          "Tags": [],
          "EnableECSManagedTags": true
        },
        "DependsOn": [
          "Listener"
        ]
      },
      "LoadBalancer": {
        "Type": "AWS::ElasticLoadBalancingV2::LoadBalancer",
        "Properties": {
          "Type": "application",
          "Name": "alb-test",
          "SecurityGroups": {
            "Ref": "SecurityGroupIDs"
          },
          "Subnets": {
            "Ref": "SubnetIDs"
          }
        }
      },
      "TargetGroup": {
        "Type": "AWS::ElasticLoadBalancingV2::TargetGroup",
        "Properties": {
          "HealthCheckPath": "/",
          "Name": "ecs-task-m-alb",
          "Port": 80,
          "Protocol": "HTTP",
          "TargetType": "ip",
          "HealthCheckProtocol": "HTTP",
          "VpcId": {
            "Ref": "VpcID"
          },
          "TargetGroupAttributes": [
            {
              "Key": "deregistration_delay.timeout_seconds",
              "Value": "300"
            }
          ]
        }
      },
      "Listener": {
        "Type": "AWS::ElasticLoadBalancingV2::Listener",
        "Properties": {
          "DefaultActions": [
            {
              "Type": "forward",
              "TargetGroupArn": {
                "Ref": "TargetGroup"
              }
            }
          ],
          "LoadBalancerArn": {
            "Ref": "LoadBalancer"
          },
          "Port": 80,
          "Protocol": "HTTP"
        }
      }
    },
    "Outputs": {
      "ClusterName": {
        "Description": "The cluster used to create the service.",
        "Value": {
          "Ref": "ECSCluster"
        }
      },
      "ECSService": {
        "Description": "The created service.",
        "Value": {
          "Ref": "ECSService"
        }
      },
      "LoadBalancer": {
        "Description": "The created load balancer.",
        "Value": {
          "Ref": "LoadBalancer"
        }
      },
      "Listener": {
        "Description": "The created listener.",
        "Value": {
          "Ref": "Listener"
        }
      },
      "TargetGroup": {
        "Description": "The created target group.",
        "Value": {
          "Ref": "TargetGroup"
        }
      }
    }
  }

YAML

AWSTemplateFormatVersion: 2010-09-09
Description: The template used to create an ECS Service associated with an
  Application Load Balancer.
Parameters:
  SecurityGroupIDs:
    Type: CommaDelimitedList
    Default: sg-1234567890abcdef0,sg-021345abcdef67890
  SubnetIDs:
    Type: CommaDelimitedList
    Default: subnet-abcdef01234567890,subnet-fedcba01234567098,subnet-2135647890abcdef0
  VpcID:
    Type: String
    Default: vpc-3214789650abcdef0
Resources:
  ECSCluster:
    Type: AWS::ECS::Cluster
    Properties:
      ClusterName: ALBCluster
  ECSService:
    Type: AWS::ECS::Service
    Properties:
      Cluster:
        Ref: ECSCluster
      TaskDefinition: arn:aws:ecs:us-east-1:111122223333:task-definition/first-run-task:7
      LaunchType: FARGATE
      ServiceName: alb
      SchedulingStrategy: REPLICA
      DesiredCount: 3
      LoadBalancers:
        - ContainerName: first-run-task
          ContainerPort: 80
          LoadBalancerName:
            Ref: AWS::NoValue
          TargetGroupArn:
            Ref: TargetGroup
      HealthCheckGracePeriodSeconds: "20"
      NetworkConfiguration:
        AwsvpcConfiguration:
          AssignPublicIp: ENABLED
          SecurityGroups:
            Ref: SecurityGroupIDs
          Subnets:
            Ref: SubnetIDs
      PlatformVersion: LATEST
      DeploymentConfiguration:
        MaximumPercent: 200
        MinimumHealthyPercent: 100
        DeploymentCircuitBreaker:
          Enable: true
          Rollback: true
      DeploymentController:
        Type: ECS
      ServiceConnectConfiguration:
        Enabled: false
      Tags: []
      EnableECSManagedTags: true
    DependsOn:
      - Listener
  LoadBalancer:
    Type: AWS::ElasticLoadBalancingV2::LoadBalancer
    Properties:
      Type: application
      Name: alb-test
      SecurityGroups:
        Ref: SecurityGroupIDs
      Subnets:
        Ref: SubnetIDs
  TargetGroup:
    Type: AWS::ElasticLoadBalancingV2::TargetGroup
    Properties:
      HealthCheckPath: /
      Name: ecs-task-m-alb
      Port: 80
      Protocol: HTTP
      TargetType: ip
      HealthCheckProtocol: HTTP
      VpcId:
        Ref: VpcID
      TargetGroupAttributes:
        - Key: deregistration_delay.timeout_seconds
          Value: "300"
  Listener:
    Type: AWS::ElasticLoadBalancingV2::Listener
    Properties:
      DefaultActions:
        - Type: forward
          TargetGroupArn:
            Ref: TargetGroup
      LoadBalancerArn:
        Ref: LoadBalancer
      Port: 80
      Protocol: HTTP
Outputs:
  ClusterName:
    Description: The cluster used to create the service.
    Value:
      Ref: ECSCluster
  ECSService:
    Description: The created service.
    Value:
      Ref: ECSService
  LoadBalancer:
    Description: The created load balancer.
    Value:
      Ref: LoadBalancer
  Listener:
    Description: The created listener.
    Value:
      Ref: Listener
  TargetGroup:
    Description: The created target group.
    Value:
      Ref: TargetGroup

Create a service with a health check grace period

The following example creates a service with a parameter that enables users to specify how many seconds that the Amazon ECS service scheduler should ignore unhealthy Elastic Load Balancing target health checks after a task has first started.

JSON

{
  "AWSTemplateFormatVersion" : "2010-09-09",
  "Description" : "Creating ECS service",
  "Parameters": {
    "AppName": {
      "Type":"String",
      "Description": "Name of app requiring ELB exposure",
      "Default": "simple-app"
    },
    "AppContainerPort": {
      "Type":"Number",
      "Description": "Container port of app requiring ELB exposure",
      "Default": "80"
    },
    "AppHostPort": {
      "Type":"Number",
      "Description": "Host port of app requiring ELB exposure",
      "Default": "80"
    },
    "ServiceName": {
      "Type": "String"
    },
    "LoadBalancerName": {
      "Type": "String"
    },
    "HealthCheckGracePeriodSeconds": {
      "Type": "String"
    }
  },
  "Resources": {
    "ECSCluster": {
      "Type": "AWS::ECS::Cluster"
    },
    "taskdefinition": {
      "Type": "AWS::ECS::TaskDefinition",
      "Properties" : {
        "ContainerDefinitions" : [
          {
            "Name": {"Ref": "AppName"},
            "MountPoints": [
              {
                "SourceVolume": "my-vol",
                "ContainerPath": "/var/www/my-vol"
              }
            ],
            "Image":"amazon/amazon-ecs-sample",
            "Cpu": "10",
            "PortMappings":[
              {
                "ContainerPort": {"Ref":"AppContainerPort"},
                "HostPort": {"Ref":"AppHostPort"}
              }
            ],
            "EntryPoint": [
              "/usr/sbin/apache2",
              "-D",
              "FOREGROUND"
            ],
            "Memory":"500",
            "Essential": "true"
          },
          {
            "Name": "busybox",
            "Image": "busybox",
            "Cpu": "10",
            "EntryPoint": [
              "sh",
              "-c"
            ],
            "Memory": "500",
            "Command": [
              "/bin/sh -c \"while true; do /bin/date > /var/www/my-vol/date; sleep 1; done\""
            ],
            "Essential" : "false",
            "VolumesFrom": [
              {
                "SourceContainer": {"Ref":"AppName"}
              }
            ]
          }
        ],
        "Volumes": [
          {
            "Host": {
              "SourcePath": "/var/lib/docker/vfs/dir/"
            },
            "Name": "my-vol"
          }
        ]
      }
    },
    "ECSService": {
      "Type": "AWS::ECS::Service",
      "Properties" : {
        "Cluster": {"Ref": "ECSCluster"},
        "DeploymentConfiguration": {
          "MaximumPercent": 200,
          "MinimumHealthyPercent": 100
        },
        "DesiredCount": 1,
        "HealthCheckGracePeriodSeconds": {"Ref": "HealthCheckGracePeriodSeconds"},
        "LoadBalancers": [{
          "ContainerName": {"Ref" : "AppName"},
          "ContainerPort": {"Ref":"AppContainerPort"},
          "LoadBalancerName": {"Ref": "elb"}
        }],
        "PlacementStrategies": [{
          "Type" : "binpack",
          "Field": "memory"
        }, {
          "Type": "spread",
          "Field": "host"
        }],
        "PlacementConstraints": [{
          "Type": "memberOf",
          "Expression": "attribute:ecs.availability-zone != us-east-1d"
        }, {
          "Type": "distinctInstance"
        }],
        "TaskDefinition" : {"Ref":"taskdefinition"},
        "ServiceName": {"Ref": "ServiceName"},
        "Role": {"Ref": "Role"}
      }
    },
    "elb": {
      "Type": "AWS::ElasticLoadBalancing::LoadBalancer",
      "Properties": {
        "LoadBalancerName": {"Ref": "LoadBalancerName"},
        "Listeners": [{
          "InstancePort": {"Ref": "AppHostPort"},
          "LoadBalancerPort": "80",
          "Protocol": "HTTP"
        }],
        "Subnets": [{"Ref":"Subnet1"}]
      },
      "DependsOn": "GatewayAttachment"
    },
    "VPC": {
      "Type": "AWS::EC2::VPC",
      "Properties": {
        "CidrBlock": "10.0.0.0/24"
      }
    },
    "Subnet1": {
      "Type": "AWS::EC2::Subnet",
      "Properties": {
        "VpcId": { "Ref": "VPC" },
        "CidrBlock": "10.0.0.0/25"
      }
    },
    "InternetGateway": {
      "Type": "AWS::EC2::InternetGateway"
    },
    "GatewayAttachment": {
      "Type": "AWS::EC2::VPCGatewayAttachment",
      "Properties": {
        "InternetGatewayId": {"Ref": "InternetGateway"},
        "VpcId": {"Ref": "VPC"}
      }
    },
    "Role": {
      "Type": "AWS::IAM::Role",
      "Properties": {
        "AssumeRolePolicyDocument": {
          "Version": "2008-10-17",
          "Statement": [
            {
              "Sid": "",
              "Effect": "Allow",
              "Principal": {
                "Service": "ecs.amazonaws.com"
              },
              "Action": "sts:AssumeRole"
            }
          ]
        },
        "ManagedPolicyArns": ["arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceRole"]
      }
    }
  },
  "Outputs" : {
    "Cluster": {
      "Value": {"Ref" : "ECSCluster"}
    }
  }
}

YAML

AWSTemplateFormatVersion: 2010-09-09
Description: Creating ECS service
Parameters:
  AppName:
    Type: String
    Description: Name of app requiring ELB exposure
    Default: simple-app
  AppContainerPort:
    Type: Number
    Description: Container port of app requiring ELB exposure
    Default: '80'
  AppHostPort:
    Type: Number
    Description: Host port of app requiring ELB exposure
    Default: '80'
  ServiceName:
    Type: String
  LoadBalancerName:
    Type: String
  HealthCheckGracePeriodSeconds:
    Type: String
Resources:
  cluster:
    Type: AWS::ECS::Cluster
  taskdefinition:
    Type: AWS::ECS::TaskDefinition
    Properties:
      ContainerDefinitions:
        - Name: !Ref AppName
          MountPoints:
            - SourceVolume: my-vol
              ContainerPath: /var/www/my-vol
          Image: amazon/amazon-ecs-sample
          Cpu: '10'
          PortMappings:
            - ContainerPort: !Ref AppContainerPort
              HostPort: !Ref AppHostPort
          EntryPoint:
            - /usr/sbin/apache2
            - '-D'
            - FOREGROUND
          Memory: '500'
          Essential: true
        - Name: busybox
          Image: busybox
          Cpu: '10'
          EntryPoint:
            - sh
            - '-c'
          Memory: '500'
          Command:
            - >-
              /bin/sh -c "while true; do /bin/date > /var/www/my-vol/date; sleep
              1; done"
          Essential: false
          VolumesFrom:
            - SourceContainer: !Ref AppName
      Volumes:
        - Host:
            SourcePath: /var/lib/docker/vfs/dir/
          Name: my-vol
  service:
    Type: AWS::ECS::Service
    Properties:
      Cluster: !Ref cluster
      DeploymentConfiguration:
        MaximumPercent: 200
        MinimumHealthyPercent: 100
      DesiredCount: 1
      HealthCheckGracePeriodSeconds: !Ref HealthCheckGracePeriodSeconds
      LoadBalancers:
        - ContainerName: !Ref AppName
          ContainerPort: !Ref AppContainerPort
          LoadBalancerName: !Ref elb
      PlacementStrategies:
        - Type: binpack
          Field: memory
        - Type: spread
          Field: host
      PlacementConstraints:
        - Type: memberOf
          Expression: 'attribute:ecs.availability-zone != us-east-1d'
        - Type: distinctInstance
      TaskDefinition: !Ref taskdefinition
      ServiceName: !Ref ServiceName
      Role: !Ref Role
  elb:
    Type: AWS::ElasticLoadBalancing::LoadBalancer
    Properties:
      LoadBalancerName: !Ref LoadBalancerName
      Listeners:
        - InstancePort: !Ref AppHostPort
          LoadBalancerPort: '80'
          Protocol: HTTP
      Subnets:
        - !Ref Subnet1
    DependsOn: GatewayAttachment
  VPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.0.0.0/24
  Subnet1:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
      CidrBlock: 10.0.0.0/25
  InternetGateway:
    Type: AWS::EC2::InternetGateway
  GatewayAttachment:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties:
      InternetGatewayId: !Ref InternetGateway
      VpcId: !Ref VPC
  Role:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: 2008-10-17
        Statement:
          - Sid: ''
            Effect: Allow
            Principal:
              Service: ecs.amazonaws.com
            Action: 'sts:AssumeRole'
      ManagedPolicyArns:
        - 'arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceRole'
Outputs:
  Cluster:
    Value: !Ref cluster

Create a service with ECS Exec enabled

The following example defines a service with ECS Exec enabled that uses a task definition that is defined in the template and runs in a cluster that is defined in the template. ReplaceExecutionRoleArn, TaskRoleArn,SecurityGroups, and Subnets with your own information. For more information, see Monitor Amazon ECS containers with ECS Exec in the Amazon ECS Developer Guide.

JSON

{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Resources": {
        "ECSCluster": {
            "Type": "AWS::ECS::Cluster",
            "Properties": {
                "ClusterName": "ExecCluster"
            }
        },
        "ECSTaskDefinition": {
            "Type": "AWS::ECS::TaskDefinition",
            "Properties": {
                "ContainerDefinitions": [
                    {
                        "Command": [
                            "/bin/sh -c \"echo '<html> <head> <title>Amazon ECS Sample App</title> <style>body {margin-top: 40px; background-color: #333;} </style> </head><body> <div style=color:white;text-align:center> <h1>Amazon ECS Sample App</h1> <h2>Congratulations!</h2> <p>Your application is now running on a container in Amazon ECS.</p> </div></body></html>' >  /usr/local/apache2/htdocs/index.html && httpd-foreground\""
                        ],
                        "EntryPoint": [
                            "sh",
                            "-c"
                        ],
                        "Essential": true,
                        "Image": "public.ecr.aws/docker/library/httpd:2.4",
                        "LogConfiguration": {
                            "LogDriver": "awslogs",
                            "Options": {
                                "awslogs-group": "/ecs/fargate-task-definition",
                                "awslogs-region": "us-east-1",
                                "awslogs-stream-prefix": "ecs"
                            }
                        },
                        "Name": "sample-fargate-app",
                        "PortMappings": [
                            {
                                "ContainerPort": 80,
                                "HostPort": 80,
                                "Protocol": "tcp"
                            }
                        ]
                    }
                ],
                "Cpu": 256,
                "ExecutionRoleArn": "arn:aws:iam::111122223333:role/ecsTaskExecutionRole",
                "TaskRoleArn":"arn:aws:iam::111122223333:role/execRole"
                "Family": "task-definition-exec",
                "Memory": 512,
                "NetworkMode": "awsvpc",
                "RequiresCompatibilities": [
                    "FARGATE"
                ],
                "RuntimePlatform": {
                    "OperatingSystemFamily": "LINUX"
                }
            }
        },
        "ECSService": {
            "Type": "AWS::ECS::Service",
            "Properties": {
                "ServiceName": "exec-service",
                "Cluster": {
                    "Ref": "ECSCluster"
                },
                "DesiredCount": 1,
                "LaunchType": "FARGATE",
                "EnableExecuteCommand": "true",
                "NetworkConfiguration": {
                    "AwsvpcConfiguration": {
                        "AssignPublicIp": "ENABLED",
                        "SecurityGroups": [
                            "sg-abcdef01234567890"
                        ],
                        "Subnets": [
                            "subnet-021345abcdef67890"
                        ]
                    }
                },
                "TaskDefinition": {
                    "Ref": "ECSTaskDefinition"
                }
            }
        }
    }
} 

YAML

AWSTemplateFormatVersion: 2010-09-09
Resources:
  ECSCluster:
    Type: 'AWS::ECS::Cluster'
    Properties:
      ClusterName: ExecCluster
  ECSTaskDefinition:
    Type: 'AWS::ECS::TaskDefinition'
    Properties:
      ContainerDefinitions:
        - Command:
            - >-
              /bin/sh -c "echo '<html> <head> <title>Amazon ECS Sample
              App</title> <style>body {margin-top: 40px; background-color:
              #333;} </style> </head><body> <div
              style=color:white;text-align:center> <h1>Amazon ECS Sample
              App</h1> <h2>Congratulations!</h2> <p>Your application is now
              running on a container in Amazon ECS.</p> </div></body></html>' > 
              /usr/local/apache2/htdocs/index.html && httpd-foreground"
          EntryPoint:
            - sh
            - '-c'
          Essential: true
          Image: 'public.ecr.aws/docker/library/httpd:2.4'
          LogConfiguration:
            LogDriver: awslogs
            Options:
              awslogs-group: /ecs/fargate-task-definition
              awslogs-region: us-east-1
              awslogs-stream-prefix: ecs
          Name: sample-fargate-app
          PortMappings:
            - ContainerPort: 80
              HostPort: 80
              Protocol: tcp
      Cpu: 256
      ExecutionRoleArn: 'arn:aws:iam::111122223333:role/ecsTaskExecutionRole'
      TaskRoleArn: arn:aws:iam::111122223333:role/execCommandRole
      Family: task-definition-exec
      Memory: 512
      NetworkMode: awsvpc
      RequiresCompatibilities:
        - FARGATE
      RuntimePlatform:
        OperatingSystemFamily: LINUX
  ECSService:
    Type: 'AWS::ECS::Service'
    Properties:
      ServiceName: exec-service
      Cluster: !Ref ECSCluster
      DesiredCount: 1
      EnableExecuteCommand: "true"
      LaunchType: FARGATE
      NetworkConfiguration:
        AwsvpcConfiguration:
          AssignPublicIp: ENABLED
          SecurityGroups:
            - sg-abcdef01234567890
          Subnets:
            - subnet-021345abcdef67890
      TaskDefinition: !Ref ECSTaskDefinition