LoginSignup
0
1
はじめての記事投稿

buildspec.ymlって何を書いているのか調べてみた

Posted at

buildspec.ymlとは

CI/CDで実行する際のコマンドを記述したYAML形式のファイルのこと。
CodePipelineで指定したソースコード内に配置し、Buildやデプロイをする際に読み込まれる。
ソースコードのルートディレクトリに配置しないとうまく動かない。
ファイル名と場所も変更できるらしい

buildspec.ymlの全体像

これはhtmlファイルをdockerコマンドでビルドして、ECRにデプロイするやつ

buildspec.yml
version: 0.2

phases:
  pre_build:
    commands:
      - echo Logging in to Amazon ECR...
      - aws --version
      - aws ecr get-login-password --region $AWS_DEFAULT_REGION | docker login --username AWS --password-stdin <AWSアカウントID>.dkr.ecr.ap-northeast-1.amazonaws.com
      - REPOSITORY_URI=<AWSアカウントID>.dkr.ecr.ap-northeast-1.amazonaws.com/ecsautodeployrepo
      - 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`
      - echo Pushing the Docker images...
      - docker push $REPOSITORY_URI:latest
      - docker push $REPOSITORY_URI:$IMAGE_TAG
      - echo Writing image definitions file...
      - printf '[{"name":"ecsAutoDeployRepo","imageUri":"%s"}]' $REPOSITORY_URI:$IMAGE_TAG > imagedefinitions.json
artifacts:
    files: imagedefinitions.json

version

0.2がAWS公式で推奨されている

phases

ビルド時にCodeBuildが実行するコマンド

pre_build

ビルドの前に実行するコマンド
Amazon ECRやDockerレジストリにログインしたり、npmの依存関係をインストールするらしい

commands

実際に実行するコマンド
上から順に実行される

aws ecr get-login-password --region $AWS_DEFAULT_REGION | docker login --username AWS --password-stdin <AWSアカウントID>.dkr.ecr.ap-northeast-1.amazonaws.com

aws ecr get-login-passwordでAmazon ECRにログインして、docker loginでECRから持ってきたパスワードで認証

REPOSITORY_URI=<AWSアカウントID>.dkr.ecr.ap-northeast-1.amazonaws.com/ecsautodeployrepo

REPOSITORY_URIを定義し、後でECRを操作するときに使う

COMMIT_HASH=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c 1-7)

$CODEBUILD_RESOLVED_SOURCE_VERSIONはAWSが事前に定義している環境変数
イメージタグを作るときに使う

build

ビルド中にCodeBuildが実行するコマンド

docker build -t $REPOSITORY_URI:latest .

ファイルをビルドする

docker tag $REPOSITORY_URI:latest $REPOSITORY_URI:$IMAGE_TAG

post_build

ビルドの後にCodeBuildが実行するコマンド
パッケージ化したり、DockerイメージをAmazon ECRにプッシュしたり、Amazon SNSで通知したりするらしい

docker push $REPOSITORY_URI:latest

Amazon ECRにDockerイメージをプッシュする

artifacts

「ビルド出力を見つけることができる場所に関する情報」と公式ドキュメントに書いてあったがよくわからない
imagedefinitions.jsonはコンテナ名とイメージ、タグについて説明するJSONファイル
以下の情報を記入する(post_buildで作成)

キー
name [コンテナ名]
ImageURI [イメージのURI]

参考

0
1
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
0
1