Rajesh Rajendran
Rajesh Rajendran

Reputation: 607

git commit hash in dockerfile as label

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?

Upvotes: 18

Views: 9276

Answers (2)

bsplosion
bsplosion

Reputation: 2866

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.

Upvotes: 0

Rajesh Rajendran
Rajesh Rajendran

Reputation: 607

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

Upvotes: 21

Related Questions