Creating Amazon ECS resources using the Amazon CloudFormation console - Amazon Elastic Container Service
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Creating Amazon ECS resources using the Amazon CloudFormation console

One way to use Amazon ECS with Amazon CloudFormation is through the Amazon Web Services Management Console. Here you can create your Amazon CloudFormation stacks for Amazon ECS components like task definitions, clusters, and services and deploy them directly from the console. The following tutorial shows how you can use the Amazon CloudFormation console to create an Amazon ECS service, task definition, and cluster.

Prerequisites

This tutorial assumes that the following prerequisites have ben completed.

Step 1: Create a stack template

Use the following steps to create a Amazon CloudFormation stack template for an Amazon ECS service and other related resources.

  1. Using a text editor of your choice, create a file called ecs-tutorial-template.yaml.

  2. In the ecs-tutorial-template.yaml file, paste the following template and save the changes.

    AWSTemplateFormatVersion: 2010-09-09 Description: A template that deploys an application that is built on an Apache web server Docker image by creating an Amazon ECS cluster, task definition, and service. The template also creates networking and logging resources, and an Amazon ECS task execution role. Parameters: ClusterName: Type: String Default: CFNCluster Description: Name of the ECS Cluster TaskFamily: Type: String Default: task-definition-cfn Description: Family name for the Task Definition ServiceName: Type: String Default: cfn-service Description: Name of the ECS Service ContainerImage: Type: String Default: public.ecr.aws/docker/library/httpd:2.4 Description: Container image to use for the task TaskCpu: Type: Number Default: 256 AllowedValues: [256, 512, 1024, 2048, 4096] Description: CPU units for the task TaskMemory: Type: Number Default: 512 AllowedValues: [512, 1024, 2048, 4096, 8192, 16384] Description: Memory (in MiB) for the task DesiredCount: Type: Number Default: 1 Description: Desired number of tasks to run LogGroupName: Type: String Default: /ecs/fargate-task-definition Description: CloudWatch Log Group name VpcCidr: Type: String Default: 10.0.0.0/16 Description: CIDR block for the VPC PublicSubnet1Cidr: Type: String Default: 10.0.0.0/24 Description: CIDR block for public subnet 1 PublicSubnet2Cidr: Type: String Default: 10.0.1.0/24 Description: CIDR block for public subnet 2 Resources: # VPC and Networking Resources VPC: Type: AWS::EC2::VPC Properties: CidrBlock: !Ref VpcCidr EnableDnsSupport: true EnableDnsHostnames: true Tags: - Key: Name Value: !Sub ${AWS::StackName}-VPC InternetGateway: Type: AWS::EC2::InternetGateway Properties: Tags: - Key: Name Value: !Sub ${AWS::StackName}-IGW InternetGatewayAttachment: Type: AWS::EC2::VPCGatewayAttachment Properties: InternetGatewayId: !Ref InternetGateway VpcId: !Ref VPC PublicSubnet1: Type: AWS::EC2::Subnet Properties: VpcId: !Ref VPC AvailabilityZone: !Select [0, !GetAZs ''] CidrBlock: !Ref PublicSubnet1Cidr MapPublicIpOnLaunch: true Tags: - Key: Name Value: !Sub ${AWS::StackName}-PublicSubnet1 PublicSubnet2: Type: AWS::EC2::Subnet Properties: VpcId: !Ref VPC AvailabilityZone: !Select [1, !GetAZs ''] CidrBlock: !Ref PublicSubnet2Cidr MapPublicIpOnLaunch: true Tags: - Key: Name Value: !Sub ${AWS::StackName}-PublicSubnet2 PublicRouteTable: Type: AWS::EC2::RouteTable Properties: VpcId: !Ref VPC Tags: - Key: Name Value: !Sub ${AWS::StackName}-PublicRouteTable DefaultPublicRoute: Type: AWS::EC2::Route DependsOn: InternetGatewayAttachment Properties: RouteTableId: !Ref PublicRouteTable DestinationCidrBlock: 0.0.0.0/0 GatewayId: !Ref InternetGateway PublicSubnet1RouteTableAssociation: Type: AWS::EC2::SubnetRouteTableAssociation Properties: RouteTableId: !Ref PublicRouteTable SubnetId: !Ref PublicSubnet1 PublicSubnet2RouteTableAssociation: Type: AWS::EC2::SubnetRouteTableAssociation Properties: RouteTableId: !Ref PublicRouteTable SubnetId: !Ref PublicSubnet2 # Security Group ECSSecurityGroup: Type: AWS::EC2::SecurityGroup Properties: GroupDescription: Security group for ECS tasks VpcId: !Ref VPC SecurityGroupIngress: - IpProtocol: tcp FromPort: 80 ToPort: 80 CidrIp: 0.0.0.0/0 - IpProtocol: tcp FromPort: 443 ToPort: 443 CidrIp: 0.0.0.0/0 # IAM Roles ECSTaskExecutionRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: '2012-10-17' Statement: - Effect: Allow Principal: Service: ecs-tasks.amazonaws.com Action: sts:AssumeRole ManagedPolicyArns: - arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy # CloudWatch Logs TaskLogGroup: Type: AWS::Logs::LogGroup DeletionPolicy: Retain UpdateReplacePolicy: Retain Properties: LogGroupName: !Ref LogGroupName RetentionInDays: 30 # ECS Resources ECSCluster: Type: AWS::ECS::Cluster Properties: ClusterName: !Ref ClusterName 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"s EntryPoint: - sh - '-c' Essential: true Image: !Ref ContainerImage LogConfiguration: LogDriver: awslogs Options: mode: non-blocking max-buffer-size: 25m awslogs-create-group: 'true' awslogs-group: !Ref LogGroupName awslogs-region: !Ref 'AWS::Region' awslogs-stream-prefix: ecs Name: sample-fargate-app PortMappings: - ContainerPort: 80 HostPort: 80 Protocol: tcp Cpu: !Ref TaskCpu ExecutionRoleArn: !GetAtt ECSTaskExecutionRole.Arn Family: !Ref TaskFamily Memory: !Ref TaskMemory NetworkMode: awsvpc RequiresCompatibilities: - FARGATE RuntimePlatform: OperatingSystemFamily: LINUX ECSService: Type: AWS::ECS::Service DependsOn: - PublicSubnet1RouteTableAssociation - PublicSubnet2RouteTableAssociation Properties: ServiceName: !Ref ServiceName Cluster: !Ref ECSCluster DesiredCount: !Ref DesiredCount LaunchType: FARGATE NetworkConfiguration: AwsvpcConfiguration: AssignPublicIp: ENABLED SecurityGroups: - !Ref ECSSecurityGroup Subnets: - !Ref PublicSubnet1 - !Ref PublicSubnet2 TaskDefinition: !Ref ECSTaskDefinition Outputs: ClusterName: Description: The name of the ECS cluster Value: !Ref ECSCluster TaskDefinitionArn: Description: The ARN of the task definition Value: !Ref ECSTaskDefinition ServiceName: Description: The name of the ECS service Value: !Ref ECSService VpcId: Description: The ID of the VPC Value: !Ref VPC PublicSubnet1: Description: The ID of public subnet 1 Value: !Ref PublicSubnet1 PublicSubnet2: Description: The ID of public subnet 2 Value: !Ref PublicSubnet2 SecurityGroup: Description: The ID of the security group Value: !Ref ECSSecurityGroup ExecutionRoleArn: Description: The ARN of the task execution role Value: !GetAtt ECSTaskExecutionRole.Arn

Step 2: Create a stack for Amazon ECS resources

After creating a file for the template, you can follow these steps to create a stack with the template by using the Amazon CloudFormation console.

  1. Sign in to the Amazon Web Services Management Console and open the Amazon CloudFormation console at https://console.amazonaws.cn/cloudformation.

  2. On the Stacks page, in the top right corner, choose Create stack , and then choose with new resources (standard).

  3. Choose Choose an existing template.

  4. Choose Upload a template file and then choose Choose file to pick the ecs-tutorial-template file.

    After the file is uploaded to an Amazon S3 bucket, you can choose View in Infrastructure Composer to visualize the template in Infrastructure Composer. For more information about Amazon CloudFormation templates and Infrastructure Composer, see Create templates visually with Infrastructure Composer in the Amazon CloudFormation User Guide.

  5. Choose Next.

  6. On the Specify stack details page, under Stack name, provide the following name for the stack: ecs-tutorial-stack. Leave all the values for parameters under Parameters as defaults, and then choose Next.

  7. On the Configure stack options page, under Capabilities, select the checkbox to acknowledge Amazon CloudFormation creating IAM resources. This acknowledgement is required to create the Amazon ECS task execution role as defined in the template. Leave the other settings as defaults and choose Next.

  8. Review the stack details on the Review and create page and then choose Submit to initiate stack creation.

Step 3: Verify

Use the following steps to verify the creation of Amazon ECS resources using the provided template.

  1. Sign in to the Amazon Web Services Management Console and open the Amazon CloudFormation console at https://console.amazonaws.cn/cloudformation.

  2. On the Stacks page, choose ecs-tutorial-stack.

  3. Choose the Events tab. If the event statuses say CREATE_IN_PROGRESS, wait until creation is completed and the statuses change to CREATE_COMPLETE.

  4. After event statuses flip to CREATE_COMPLETE, choose the Resources tab. You will see resources with the Logical ID ECSCluster, ECSTaskDefinition, and ECSService respectively.

  5. To verify the creation of an Amazon ECS cluster, choose the Physical ID associated with ECSCluster. You will be redirected to the Amazon ECS console where you can see the created cluster called CFNCluster.

  6. To verify the creation of an Amazon ECS service, choose the Physical ID associated with ECSService. You will be redirected to the Amazon ECS console where you can see the service called cfn-service that is created in the cluster cfnCluster.

  7. To verify the creation of an Amazon ECS task definition, choose the Physical ID associated with ECSTaskDefinition. You will be redirected to the Amazon ECS console where you can see the task definition revision with the name task-definition-cfn.

Step 4: Clean up resources

To clean up resources and avoid incurring further costs, follow these steps.

  1. Sign in to the Amazon Web Services Management Console and open the Amazon CloudFormation console at https://console.amazonaws.cn/cloudformation.

  2. On the Stacks page, choose ecs-tutorial-stack.

  3. Choose Delete.

  4. When prompted for confirmation, choose Delete again.

  5. Choose the Events tab. The Status for the ecs-tutorial-stack changes to DELETE_IN_PROGRESS and then to DELETE_COMPLETE after the resources are deleted or deregistered. The deletion takes a couple minutes.

  6. Choose the Resources tab. You will now see a list of Logical ID with the Status updated to DELETE_COMPLETE.