5
3

More than 1 year has passed since last update.

タスク定義をプッシュした最新のイメージに変更するだけのbuildspec ファイル

Posted at

概要

CodeBuild 内で、イメージのビルドとECR にプッシュし、タスク定義のコンテナのイメージURIの変更だけをして、サービスにはデプロイしないケースを想定した buildspec ファイルです。

実行に必要なビルドプロジェクトの環境変数

名前 説明
AWS_ACCOUNT_ID AWS アカウントID
IMAGE_REPO_NAME ECRのリポジトリ名
TASK_DEFINITION タスク定義名

実行に必要なIAM ポリシー

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ecs:*"
            ],
            "Resource": "*"
        },
        {
            "Action": "iam:PassRole",
            "Effect": "Allow",
            "Resource": [
                "*"
            ],
            "Condition": {
                "StringLike": {
                    "iam:PassedToService": "ecs-tasks.amazonaws.com"
                }
            }
        }
    ]
}

buildspec.yml

version: 0.2

phases:
  pre_build:
    commands:
      - echo Logging in to Amazon ECR...
      - aws --version
      - echo $AWS_DEFAULT_REGION
      - $(aws ecr get-login --region $AWS_DEFAULT_REGION --no-include-email)
      - REPOSITORY_URI=$AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_REPO_NAME
      - COMMIT_HASH=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c 1-7)
      - IMAGE_TAG=${COMMIT_HASH:=latest}
  build:
    commands:
      - echo Build started on `date`
      - echo Building the Docker image...
      - docker build -t $REPOSITORY_URI:latest .
      - docker tag $REPOSITORY_URI:latest $REPOSITORY_URI:$IMAGE_TAG
  post_build:
    commands:
      - echo Build completed on `date`
      - docker push $REPOSITORY_URI:latest
      - docker push $REPOSITORY_URI:$IMAGE_TAG
      - aws ecs describe-task-definition --task-definition ${TASK_DEFINITION} | jq '.taskDefinition | del(.taskDefinitionArn, .status, .requiresAttributes, .compatibilities, .revision)' | jq '(.containerDefinitions[] | select(.name == "'${IMAGE_REPO_NAME}'")).image = "'${REPOSITORY_URI}:${IMAGE_TAG}'"' > /tmp/taskdef.json
      - aws ecs register-task-definition --cli-input-json file:///tmp/taskdef.json
5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3