Search code examples
gitdockerdockerfile

Passing the result of a git command as an argument to docker build


I need to pass the git commit hash to a docker build so that it's further passed as an argument to dotnet build to be used as suffix for versioning packages.

Inside the dockerfile, I have something like this:

FROM ...

ARG GIT_COMMIT
ENV GIT_COMMIT=$GIT_COMMIT

...

RUN dotnet build -c Release --no-restore /p:SourceRevisionId=${GIT_COMMIT}

I'm trying to pass the GIT_COMMIT argument as follows:

docker build --build-arg GIT_COMMIT=$(git rev-parse HEAD) .

but this results in the following error:

"docker build" requires exactly 1 argument.
See 'docker build --help'.

Usage:  docker build [OPTIONS] PATH | URL | -

Build an image from a Dockerfile

What I want is the short version of the hash, so I need to pass --short to git:

docker build --build-arg GIT_COMMIT=$(git rev-parse --short HEAD) .

In this case, I get the following:

unknown flag: --short
See 'docker build --help'.

What do I have to do to get this working?


Solution

  • Looks like you are using cmd.exe. You can use:

    for /F "usebackq delims=" %A in (`git rev-parse HEAD`) do docker build --build-arg GIT_COMMIT=%A .
    

    See this answer for more information.