AWS

bitbucket pipeline을 이용한 AWS ECS 애플리케이션 배포

알쓸개잡 2023. 10. 23.

bitbucket은 aws-ecs-deploy 플러그인을 제공하여 손쉽게 AWS ECS 서비스에 애플리케이션을 배포할 수 있도록 한다.

AWS CodeDeploy나 CodePipeline을 통해서 배포할 수도 있겠지만, 이번 포스팅에서는 bitbucket pipeline을 통해서 AWS ECS에 애플리케이션을 배포하는 방법에 대해서 소개한다.

 

사전 조건

  • Docker Hub 혹은 AWS ECR과 같은 image registry가 필요하다.
  • AWS ECS Service 구성이 필요하다.
  • RegisterTaskDefinition 및 UpdateService 권한이 있는 AWS IAM 사용자가 필요하다.
  • 해당 bitbucket repository에 bitbucket pipeline 사용 설정이 필요하다.

 

AWS IAM 권한

빌드 및 배포를 수행하는 AWS IAM 계정이 있을 것인데 해당 IAM 계정에 다음과 같은 권한이 필요하다.

AWS 콘솔의 해당 IAM 계정에서 IAM > Users > 해당 계정 > Add permissions > Create inline policy를 통해서 추가한다.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "ecs:UpdateService",
                "ecs:RegisterTaskDefinition"
            ],
            "Resource": "*"
        }
    ]
}
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "iam:GetRole",
                "iam:PassRole"
            ],
            "Resource": "<ecsTaskExecutionRole arn>"
        }
    ]
}
  • <ecsTaskExecutionRole arn>은 AmazonECSTaskExecutionRolePolicy 정책을 포함하고 있는 role 이다.
  • ECS Service를 구성하였다면 AmazonECSTaskExecutionRolePolicy 정책을 포함한 role이 있을 것인데 해당 role arn을 입력한다.
  • 샘플에서는 ecsTaskExecutionRole이라고 하겠다.
  • iam:PassRole은 배포를 수행하는 IAM 계정에서 ecsTaskExecutionRole을 사용할 수 있도록 한다.

 

AmazonECSTaskExecutionRolePolicy는 다음과 같다.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ecr:GetAuthorizationToken",
                "ecr:BatchCheckLayerAvailability",
                "ecr:GetDownloadUrlForLayer",
                "ecr:BatchGetImage",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": "*"
        }
    ]
}

 

bitbucket pipeline script

우선 기본적으로 bitbucket pipeline에 대한 작성 방법을 숙지하고 있어야 한다.

atlassian/aws-ecs-deploy pipe 제공하여 AWS ECS에 손쉽게 애플리케이션을 배포할 수 있다.

AWS ECR에 애플리케이션을 배포하는 script는 다음과 같다.

pipelines:
  branches:
    master:
      - step:
          <애플리케이션 빌드 및 ECR에 배포코드>
      - step:
          script:
            - pipe: atlassian/aws-ecs-deploy:1.0.0
              variables:
                AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY
                AWS_SECRET_ACCESS_KEY: $AWS_SECRET_KEY
                AWS_DEFAULT_REGION: $AWS_REGION
                CLUSTER_NAME: <ECS cluster 이름>
                SERVICE_NAME: <ECS service 이름>
                TASK_DEFINITION: <ECS service에 적용된 task definition json 파일>

$AWS_ACCESS_KEY, $AWS_SECRET_KEY, $AWS_REGION은 bitbucket repository의 variable로 등록한다.

variable 이름을 $AWS_ACCESS_KEY_ID, $AWS_SECRET_ACCESS_KEY, $AWS_DEFAULT_REGION으로 사용한다면 bitbucket-pipelines.yml의 variables에 따로 지정하지 않아도 된다.

script:
  - pipe: atlassian/aws-ecs-deploy:1.9.0
    variables:
      CLUSTER_NAME: 'my-ecs-cluster'
      SERVICE_NAME: 'my-ecs-service'
      TASK_DEFINITION: 'task-definition.json'

 

ECS service에 적용된 task definition json 파일은 AWS 콘솔에서 ECS >> Task definitions에서 JSON 파일로 다운로드한다.

task definition json 파일 샘플은 다음과 같다.

{
    "containerDefinitions": [
        {
            "name": "<task 이름>",
            "image": "<ECR container image 경로>:<version>",
            "portMappings": [
                {
                    "containerPort": <application port>,
                    "hostPort": <host port>,
                    "protocol": "tcp"
                }
            ],
            "essential": true,
            "environment": [
                {
                    "name": "SPRING_PROFILES_ACTIVE",
                    "value": "production"
                }
            ]
        }
    ],
    "family": "<family name>",
    "taskRoleArn": "<ecsTaskExecutionRole arn>",
    "executionRoleArn": "<ecsTaskExecutionRole arn>",
    "networkMode": "awsvpc",
    "volumes": [],
    "requiresCompatibilities": [
        "FARGATE"
    ],
    "cpu": "1024",
    "memory": "2048",
    "tags": [
        {
            "key": "<tag key>",
            "value": "<tag value>"
        },
        ...
    ]
}

 

bitbucket repository에 코드를 commit 하고 pipeline 수행이 완료된 후 AWS ECS에서 배포 로그는 다음과 같다.

ECS > Clusters > 클러스터이름 > Services > 서비스 이름 > Deployments

 


참고링크

https://support.atlassian.com/bitbucket-cloud/docs/deploy-to-amazon-ecs/

 

Deploy to Amazon ECS | Bitbucket Cloud | Atlassian Support

This option provides you with a simplified way of deploying to ECS. It requires less maintenance since the pipeline is maintained on your behalf.

support.atlassian.com

https://bitbucket.org/bitbucketpipelines/example-aws-ecs-deploy/src/master/

 

Bitbucket

 

bitbucket.org

https://docs.aws.amazon.com/AmazonECS/latest/developerguide/using-service-linked-roles.html

 

Using service-linked roles for Amazon ECS - Amazon Elastic Container Service

If you are unsure whether Amazon ECS is using the AWSServiceRoleForECS role, you can try to delete the role. If the service is using the role, then the deletion fails and you can view the regions where the role is being used. If the role is being used, the

docs.aws.amazon.com

 

댓글

💲 추천 글