18

How to add git commit hash or any other dynamically inferred value in Dockerfile.

LABEL vcs-ref=$(git rev-parse --short HEAD)

Something like this?

Rajesh Rajendran
  • 587
  • 5
  • 18

2 Answers2

19

I found it atlast,

use docker build --build-arg vcs-ref=$(git rev-parse --short HEAD)

while building.

But have to initialize the variable in vcs-ref in Dockerfile

ARG vcs-ref=0
ENV vcs-ref=$vcs-ref
Rajesh Rajendran
  • 587
  • 5
  • 18
  • If you're using Windows, it might be easiest to do this from a bash terminal (as opposed to Windows cmd) – JoeyC Jun 03 '19 at 07:40
  • Finally, what is the complete answer here? ARG, ENV, --buiid-arg all required? A sample snippet with required build-arg would help – nashter Jul 31 '20 at 07:25
  • @dexter2305 , all is required. `--build-arg` passes the git hash value into `ARG`, docker passes it from build time `ARG` to runtime `ENV`, your application reads `ENV`. Btw, ARG and ENV should be in one `FROM` block to see each other. – homk Sep 08 '20 at 21:39
0

For poor suckers like myself who have to make this happen in Windows CMD, and especially for those who are doing so via NPM, here's a viable approach:

git rev-parse --short HEAD > tmpCommitFile && set /p GIT_COMMIT= < tmpCommitFile && del tmpCommitFile && docker build --build-arg vcs-ref=%GIT_COMMIT%

This combines the usage of git rev-parse HEAD, this answer for some ideas about how to read command output in CMD into a variable, and finally how to pass it as an arg as noted on the other answer here. CMD makes this much more challenging than expected.

You can feed the %GIT_COMMIT% as an argument into whatever you have for a build script instead if there's a layer of abstraction before Docker.

bsplosion
  • 2,641
  • 27
  • 38