AWS CLI コマンドを使用した AWS CloudFormation の Amazon ECS リソースの作成
次のチュートリアルでは、AWS CLI を使用して AWS CloudFormation テンプレートで Amazon ECS リソースを作成する方法を学習します。
前提条件
-
「Amazon ECS を使用するようにセットアップする」のステップを完了していること。
-
IAM ユーザーに AmazonECS_FullAccess IAM ポリシー例で指定されている必要なアクセス権限があること。
ステップ 1: スタックを作成する
AWS CLI を使用してスタックを作成するには、次の手順に従ってください。
-
お好きなテキストエディタを使用して、
ecs-tutorial-template.yaml
という名前のファイルを作成します。 -
ecs-tutorial-template.yaml
ファイルに次のテンプレートを貼り付けて、変更を保存します。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
-
テンプレートファイルを作成したら、次のコマンドを使用してスタックを作成します。テンプレートで指定した Amazon ECS タスク実行ロールを作成するには、
--capabilities
フラグが必要です。--parameters
フラグを指定して、テンプレートパラメータをカスタマイズすることもできます。aws cloudformation create-stack \ --stack-name
ecs-stack
\ --template-body file://ecs-tutorial-template.yaml
\ --capabilities CAPABILITY_IAM
ステップ 2: リソースの作成を確認する
リソースが正しく作成されていることを確認するには、次の手順に従います。Amazon ECS コンソールをチェックすることもできます。
-
次のコマンドを実行して、AWS リージョン 内のすべてのタスク定義を一覧表示します。
aws ecs list-task-definitions
コマンドは、タスク定義の Amazon リソースネーム (ARN) のリストを返します。テンプレートを使用して作成したタスク定義の ARN は、次の形式で表示されます。
{ "taskDefinitionArns": [ ..... "arn:aws:ecs:
aws-region
:111122223333
:task-definition/task-definition-cfn:1", ..... ] } -
次のコマンドを実行して、AWS リージョン 内のすべてのクラスターを一覧表示します。
aws ecs list-clusters
コマンドはクラスター ARN のリストを返します。テンプレートを使用して作成したクラスターの ARN は、次の形式で表示されます。
{ "clusterArns": [ ..... "arn:aws:ecs:
aws-region
:111122223333
:cluster/CFNCluster", ..... ] } -
クラスター
CFNCluster
内のすべてのサービスを一覧表示するには、次のコマンドを実行します。aws ecs list-services \ --cluster
CFNCluster
コマンドは、サービス ARN のリストを返します。テンプレートを使用して作成されたサービスの ARN は、次の形式で表示されます。
{ "serviceArns": [ "arn:aws:ecs:
aws-region
:111122223333
:service/CFNCluster/cfn-service" ] }
ステップ 3: クリーンアップする
作成したリソースをクリーンアップするには、以下のコマンドを実行します。
aws cloudformation delete-stack \ --stack-name
ecs-stack
delete-stack
コマンドは、このチュートリアルで作成した AWS CloudFormation スタックの削除を開始し、スタック内のすべてのリソースを削除します。削除を確認するには、ステップ 2: リソースの作成を確認する で同じ手順を繰り返します。出力内の ARN のリストには、task-definition-cfn
というタスク定義や CFNCLuster
という名前のクラスターが含まれなくなります。list-services
呼び出しは失敗します。