Jenkins – Interpolate Environment Variables Inside Dockerfile

dockerenvironment-variablesJenkins

I have a Jenkins pipeline,
One of the stages of the pipeline is to build the artifact from a java application code.
The artifact always get the name hello-world-${BUILD_ID}.war using BUILD_ID jenkins environment variable for every build the name of the artifact will be changed.

Than, I have another stage in which I have to build a docker image for this artifact.
One of the lines of the Docker file is:
COPY hello-world-war-1.0.${BUILD_ID}.war /usr/local/tomcat/webapps/java-app.war
In this line I have to copy the artifact to to the docker images.

For some reason, the mentioned interpolation doesn't work and when I run the pipeline I get the same error:
COPY failed: stat hello-world-war-1.0..war: no such file or directory

Of course, when I hard code the number of the build id inside the Dockerfile, all work well.

Attached is a screenshot of the whole the Dockerfile.

Thanks in advance for any help !

enter image description here

Best Answer

You must pass your BUILD_ID as a build argument.

In your Dockerfile:

ARG BUILD_ID

In your docker build command:

docker build ... --build-arg BUILD_ID="${BUILD_ID}" ...

Environment variables like ${BUILD_ID} are not passed to Dockerfile commands. This is voluntary, because docker build shoud be as reproducible as possible, without being dependent on build context. If you want a variable in the build process, it must be set explicitly.