How to assign the git rev-parse output to ENV variable in dockerfile?

707 Views Asked by At

I am trying to add versioning to my program, and I want the version string to be the short commit hash of my repo.

The following command gives me exactly the string I want: git rev-parse --short HEAD.

So far, I was able to set it as an environment variable by having the following lines in my Dockerfie:

ARG VERSION_NUM
ENV VERSION_NUM=$VERSION_NUM

And the following build command: docker-compose build --build-arg VERSION_NUM=$(git rev-parse --short HEAD)

In my main.py I have this assignment and it works: VERSION_NUM = os.environ.get('VERSION_NUM', 'local_version')

But now, I need to change the code and find another way to do this without passing the --build-arg when building the container.

What is the correct way to do so? CI\CD-wise and practice-wise..

I have tried two methods so far:

  1. I created a set_version.sh script that exports the variable (the short commit hash) - but it did not take place.
  2. I created a get_version.sh script that outputs the variable but I wasn't able to assign it to an ENV variable.
1

There are 1 best solutions below

2
Neil Barnwell On

I did this work outside the docker build pipeline, and passed the value in as an ARG.

Apologies this is in PowerShell but I'm not much good at Bash. I'm sure you can translate to something useful to you though.

dotnet tool install --global GitVersion.Tool
$version = dotnet-gitversion | convertfrom-json | select -exp Semver

docker build -t "my-app:$($version)" --build-arg "VERSION_NUM=$($version)"

UPDATE: I made a guess how you'd do without gitversion:

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

docker build -t "my-app:$($version)" --build-arg "VERSION_NUM=$($version)"