Reputation: 664
I currently have two Dockerfiles that are identical except for some ENV vars at the beginning that have different values. I want to combine them into one Dockerfile and select the ENV vars depending on one build-arg / ARG instead.
I tried something like this with $target being either WIN or UNIX:
FROM alpine
ARG target
ARG VAR1_WIN=Value4Win
ARG VAR1_UNIX=Value4Unix
ARG VAR1=VAR1_$target
ARG VAR1=${!VAR1}
RUN echo $VAR1
But it throws an error: failed to process "${!VAR1}": missing ':' in substitution
I tried a lot but I'm unable to double expand $VAR1
.
How do I do this correctly? Thx.
Upvotes: 1
Views: 1438
Reputation: 263469
For the conditional syntax, there is a pattern you can use with a multi-stage build:
# ARG defined before the first FROM can be used in FROM lines
ARG target
# first base image for WIN target
FROM alpine as base-WIN
# switching to ENV since ARG doesn't pass through to the next stage
ENV VAR1=Value4Win
# second base image for UNIX target
FROM alpine as base-UNIX
ENV VAR1=Value4Unix
# select one of the above images based on the value of target
FROM base-${target} as release
RUN echo $VAR1
Upvotes: 3
Reputation: 672
The double expand syntax ${!VAR}
only works in bash
, while Dockerfile
is not parsed by shell. According to the docker manual, Dockerfile
does not support double expand.
Note that alpine
use ash
instead of bash
, so it does not support ${!VAR}
either. You have to use eval
+ echo
. Try RUN VAR1="$(eval "echo \$$VAR1")"; echo $VAR1
.
Upvotes: 0
Reputation: 1989
If you can't pass Value4Win
or Value4Unix
directly via --build-arg
, here is one way:
FROM alpine
ARG target
ARG VAR1=Value4${target}
RUN echo $VAR1
Doing a docker build --build-arg target=WIN .
gives:
Step 4/4 : RUN echo $VAR1
---> Running in 6e94bc28d459
Value4WIN
Upvotes: -1