RSS

Add git commit to docker image tag in Azure pipeline

Add git commit to docker image tag in Azure pipeline

Problem

I have Azure devops pipeline to build docker image from source. I want the docker image have the source code revision info like git commit hash.

I tried to use Build.SourceVersion as a docker image tag,

Build.SourceVersion :

The latest version control change that is included in this build.

  • Git: The commit ID.
  • TFVC: the changeset.

This variable is agent-scoped, and can be used as an environment variable in a script and as a parameter in a build task, but not as part of the build number or as a version control tag.

I set my docker image tag in Docker task as:

$(Build.SourceBranch)-$(Build.BuildId)-$(Build.SourceVersion)

Then I trigger a build, I hope it can generate tag like this:

master-8219-59af41e

However it generate tag like this (missing commit):

master-8219-

When I trigger a build, I notice there is a Commit field. I didn’t input anything and it should be the latest commit. However it seems Azure pipeline didn’t pass the latest commit to Build.SourceVersion.

Solution

To solve this issue. I use Azure pipeline environment var to pass the commit hash to docker image tag. The trick is create a Bash Script task to set environment var.

The Bash Script content as following:

GIT_COMMIT=$(git rev-parse --short HEAD)

echo "GIT_COMMIT: ${GIT_COMMIT}"

#
# set env variable to allow next task to consume
#
echo "##vso[task.setvariable variable=GIT_COMMIT]${GIT_COMMIT}"

Now in next Azure pipeline task Push Docker Image, it use access var GIT_COMMIT through $(GIT_COMMIT).

Now trigger manual build you will get docker image tag with git commit. e.g.

master-8219-59af41e

Reference