LoginSignup
6
7

More than 5 years have passed since last update.

Docker Hub で自動ビルドするときに Git のコミットIDをイメージに埋め込む

Last updated at Posted at 2019-02-16

Dockerfile からの相対で hooks/build というファイルに次のようなスクリプトを置きます。

#!/bin/bash

docker build --build-arg SOURCE_COMMIT=$SOURCE_COMMIT -f $DOCKERFILE_PATH -t $IMAGE_NAME .

例えば次のようなレイアウトです(Build Context が hoge/ な例)。

./hoge/
    Dockerfile
    hooks/
        build

DockerfileSOURCE_COMMIT がビルドの ARG として使えるようになります。

FROM busybox

ARG SOURCE_COMMIT

ENV SOURCE_COMMIT $SOURCE_COMMIT

CMD ["env"]

詳細

Advanced options for Autobuild and AutotestCustom build phase hooks を用いたものです。

hooks/build というファイルがあれば docker build の代わりに呼ばれます。このスクリプトでは以下の環境変数が利用可能です。

  • SOURCE_BRANCH: the name of the branch or the tag that is currently being tested.
    • e.g. master
  • SOURCE_COMMIT: the SHA1 hash of the commit being tested.
    • e.g. 5852b96005ac94839ac828b0771e5338cc7e9376
  • COMMIT_MSG: the message from the commit being tested and built.
    • e.g. first commit
  • DOCKER_REPO: the name of the Docker repository being built.
    • e.g. index.docker.io/your/awesome
  • DOCKERFILE_PATH: the dockerfile currently being built.
    • e.g. Dockerfile
  • CACHE_TAG: the Docker repository tag being built.
    • e.g. latest
  • IMAGE_NAME: the name and tag of the Docker repository being built. (This variable is a combination of DOCKER_REPO:CACHE_TAG.)
    • e.g. index.docker.io/your/awesome:latest

これらを docker build--build-arg で渡せば Dockerfile で ARG として使用できます。

hooks/build 以外に hooks/testhooks/push で自動ビルドの各フェーズが上書きできるようです。

また、以下のようなスクリプトでビルドの各フェーズ間に処理を挟むことができます。

  • hooks/post_checkout
  • hooks/pre_build
  • hooks/post_build
  • hooks/pre_test
  • hooks/post_test
  • hooks/pre_push
  • hooks/post_push

例えば hooks/post_push を次のような内容で作成しておけば、自動ビルドの Build Rules とは別に Git のコミットIDを Docker タグにできます。

#!/bin/bash

docker tag $IMAGE_NAME $DOCKER_REPO:$SOURCE_COMMIT
docker push $DOCKER_REPO:$SOURCE_COMMIT

参考

6
7
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
6
7