0

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.
hadar
  • 1

1 Answers1

0

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)"
Neil Barnwell
  • 41,080
  • 29
  • 148
  • 220
  • Thank you. I was already able to pass the argument from outside , now I am trying to create it on the fly inside the build. – hadar Mar 14 '23 at 09:36
  • I don't think you can. Each layer in an image is created in a new container. Even if you used RUN to execute a script to set an environment variable, I don't think it would persist to the next layer, and you'd need to have git in your base image. – Neil Barnwell Mar 14 '23 at 19:03