Is there any way to make a build argument mandatory during docker build
? The expected behaviour would be for the build to fail if the argument is missing.
For example, for the following Dockerfile:
FROM ubuntu
ARG MY_VARIABLE
ENV MY_VARIABLE $MY_VARIABLE
RUN ...
I would like the build to fail at ARG MY_VARIABLE
when built with docker build -t my-tag .
and pass when built with docker build -t my-tag --build-arg MY_VARIABLE=my_value .
.
Is there any way to achieve that behaviour? Setting a default value doesn't really do the trick in my case.
(I'm running Docker 1.11.1
on darwin/amd64
.)
EDIT:
One way of doing that I can think of is to run a command that fails when MY_VARIABLE
is empty, e.g.:
FROM ubuntu
ARG MY_VARIABLE
RUN test -n "$MY_VARIABLE"
ENV MY_VARIABLE $MY_VARIABLE
RUN ...
but it doesn't seem to be a very idiomatic solution to the problem at hand.
You could do something like this...
Then
docker build -t my_variable_base .
Then build your images based on this...
It's not super clean, but at least it abstracts the 'bleh' stuff away to the base image.
I cannot comment yet because I do not have 50 reputation, but I would like to add onto @Jan Nash's solution because I had a little difficulty getting it to work with my image.
If you copy/paste @Jan Nash's solution, it will work and spit out the error message that the build argument is not specified.
What I want to add
When I tried getting it to work on a CentOS 7 image (centos:7), Docker ran the
RUN
command without erroring out.Solution
Ensure that you're executing the
RUN
command with the bash shell.RUN ["/bin/bash", "-c", ": ${MYUID:?Build argument needs to be set and not null.}"]
I hope that helps for future incoming people. Otherwise, I believe @Jan Nash's solution is just brilliant.
You can also use shell parameter expansion to achieve this.
Let's say your mandatory build argument is called
MANDATORY_BUILD_ARGUMENT
, and you want it to be set and non-empty, your Dockerfile could look like this:Of course, you would also want to use the build-argument for something, unlike I did, but still, I recommend building this Dockerfile and taking it for a test-run :)
I tested with
RUN test -n <ARGvariablename>
what @konradstrack mentioned in the original (edit) post... that seems do the job of mandating the variable to be passed as the build time argument for thedocker build
command:Another simple way: