0

Is there a way to enable a directive of the form

ENV SOMEVAR=SOMEVALUE

...at build time, e.g. through some docker buildx build command-line flag, or through some the setting of some environment variable (in the docker buildx build process's environment)?

Alternatively, is there some way that I can modify the value that gets assigned in the ENV on the basis of some setting (flag, environment variable, etc.) at build time?

I suppose I could do something like

RUN <<EOF
#!/usr/bin/env bash
if [[ -n $SOMEVAR ]];
    printf -- "\n\nexport SOMEVAR='%s'\n\n" "$SOMEVAR" >> /root/.bashrc
fi
EOF

...and then, at build time, include the flag --build-arg "SOMEVAR=SOMEVALUE" in the docker buildx build command line to have the printf line executed during the build, but such maneuvers strike me as extremely fragile. Plus, I doubt that this comes even close to replicating the effect of the original ENV SOMEVAR=SOMEVALUE directive.

Is there a better way?

kjo
  • 33,683
  • 52
  • 148
  • 265

1 Answers1

1

Depending on the exact semantics you want, you could maybe do something that combines build arguments with environment variables, like this:

FROM docker.io/alpine:latest

ARG SOMEVAR=default_value
ENV SOMEVAR=${SOMEVAR}

If we build this like:

docker build -t envtest .

And then run it, we see:

$ docker run --rm envtest sh -c 'echo $SOMEVAR'
default_value

But if we provide a custom value at build time:

docker build -t envtest --build-arg SOMEVAR=my_custom_value .

Then we see:

$ docker run --rm envtest sh -c 'echo $SOMEVAR'
my_custom_value
larsks
  • 277,717
  • 41
  • 399
  • 399