AWS CloudFormation 콘솔을 사용하여 Amazon ECS 리소스 생성 - Amazon Elastic Container Service

AWS CloudFormation 콘솔을 사용하여 Amazon ECS 리소스 생성

AWS CloudFormation에서 Amazon ECS를 사용하는 한 가지 방법은 AWS Management Console을 사용하는 것입니다. 여기에서 태스크 정의, 클러스터, 서비스와 같은 Amazon ECS 구성 요소를 위한 AWS CloudFormation 스택을 생성하고 콘솔에서 직접 배포할 수 있습니다. 다음 자습서에서는 AWS CloudFormation 콘솔을 사용하여 Amazon ECS 서비스, 태스크 정의 및 클러스터를 생성하는 방법을 보여줍니다.

사전 조건

이 자습서에서는 다음 사전 조건이 충족되었다고 가정합니다.

1단계: 스택 템플릿 생성

다음 단계를 사용하여 Amazon ECS 서비스 및 기타 관련 리소스를 위한 AWS CloudFormation 스택 템플릿을 생성합니다.

  1. 원하는 텍스트 편집기를 사용하여 ecs-tutorial-template.yaml이라는 파일을 생성합니다.

  2. 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

2단계: Amazon ECS 리소스를 위한 스택 생성

템플릿 파일을 생성한 후 AWS CloudFormation 콘솔을 사용하여 다음 단계에 따라 템플릿으로 스택을 생성할 수 있습니다.

  1. AWS Management Console에 로그인하여 https://console.aws.amazon.com/cloudformation에서 AWS CloudFormation 콘솔을 엽니다.

  2. 스택 페이지의 오른쪽 상단에서 스택 생성을 선택하고 새 리소스 사용(표준)을 선택합니다.

  3. 기존 템플릿 선택을 선택합니다.

  4. 템플릿 파일 업로드을 선택한 다음 파일 선택을 선택하여 ecs-tutorial-template 파일을 선택합니다.

    파일이 Amazon S3 버킷에 업로드된 후 Infrastructure Composer에서 보기를 선택하여 Infrastructure Composer에서 템플릿을 시각화할 수 있습니다. AWS CloudFormation 템플릿 및 Infrastructure Composer에 대한 자세한 내용은 AWS CloudFormation 사용 설명서Infrastructure Composer를 사용하여 시각적으로 템플릿 생성을 참조하세요.

  5. 다음을 선택합니다.

  6. 스택 세부 정보 지정 페이지의 스택 이름에서 스택의 이름을 입력합니다. ecs-tutorial-stack. 파라미터 아래의 모든 파라미터 값을 기본값 그대로 두고 다음을 선택합니다.

  7. 스택 옵션 구성 페이지의 기능에서 AWS CloudFormation이 IAM 리소스를 생성하도록 승인하는 확인란을 선택합니다. 이 승인은 템플릿에 정의된 대로 Amazon ECS 태스크 실행 역할을 생성하는 데 필요합니다. 다른 모든 설정은 기본값 그대로 두고 다음을 선택합니다.

  8. 검토 및 생성 페이지에서 스택 세부 정보를 검토한 다음 제출을 선택하여 스택 생성을 시작합니다.

3단계: 확인

다음 단계에 따라 제공된 템플릿을 사용한 Amazon ECS 리소스 생성을 확인합니다.

  1. AWS Management Console에 로그인하여 https://console.aws.amazon.com/cloudformation에서 AWS CloudFormation 콘솔을 엽니다.

  2. 스택 페이지에서 ecs-tutorial-stack을 선택합니다.

  3. 이벤트 탭을 선택합니다. 이벤트 상태가 CREATE_IN_PROGRESS로 표시되면 생성이 완료되고 상태가 CREATE_COMPLETE로 변경될 때까지 기다립니다.

  4. 이벤트 상태가 CREATE_COMPLETE로 전환되면 리소스 탭을 선택합니다. 논리적 IDECSCluster, , ECSTaskDefinitionECSService인 리소스가 각각 표시됩니다.

  5. Amazon ECS 클러스터 생성을 확인하려면 ECSCluster와 연결된 물리적 ID를 선택합니다. 그러면 생성된 CFNCluster라는 클러스터를 볼 수 있는 Amazon ECS 콘솔로 리디렉션됩니다.

  6. Amazon ECS 서비스 생성을 확인하려면 ECSService와 연결된 물리적 ID를 선택합니다. 그러면 클러스터 cfnCluster에서 생성된 cfn-service라는 서비스를 볼 수 있는 Amazon ECS 콘솔로 리디렉션됩니다.

  7. Amazon ECS 태스크 정의 생성을 확인하려면 ECSTaskDefinition과 연결된 물리적 ID를 선택합니다. 그러면 이름이 task-definition-cfn인 태스크 정의 개정을 볼 수 있는 Amazon ECS 콘솔로 리디렉션됩니다.

4단계: 리소스 정리

추가 비용이 발생하지 않도록 리소스를 정리하려면 다음 단계를 수행합니다.

  1. AWS Management Console에 로그인하여 https://console.aws.amazon.com/cloudformation에서 AWS CloudFormation 콘솔을 엽니다.

  2. 스택 페이지에서 ecs-tutorial-stack을 선택합니다.

  3. 삭제를 선택합니다.

  4. 확인 메시지가 나타나면 다시 삭제를 선택합니다.

  5. 이벤트 탭을 선택합니다. 상태DELETE_IN_PROGRESS로 변경된 다음, 리소스가 삭제되거나 등록 취소돠면 DELETE_COMPLETEecs-tutorial-stack 변경됩니다. 삭제하는 데 몇 분 정도 소요됩니다.

  6. 리소스 탭을 선택합니다. 이제 상태DELETE_COMPLETE로 업데이트된 논리적 ID 목록이 표시됩니다.