How To Set Environment Variable On The Fly During Buildtime?

Hello all, I am trying to set an environment variable on the fly in a docker build. This is my Dockerfile

FROM atlassian/default-image:3
ARG CACHEBUST=1

WORKDIR /tmp
COPY ./build /tmp/build
RUN chmod -R +x /tmp/build

CMD source /tmp/build/scriptenv.sh
ENV PYTHONV $(python3 -c "exec(\"import sys\nprint(f'{sys.version_info.major}.{sys.version_info.minor}')\")")
#RUN python3 /tmp/build/setenv.py

RUN echo $PYTHONV

And the PYTHONV echoed the string, kinda expected. So I tried

FROM atlassian/default-image:3
ARG CACHEBUST=1

WORKDIR /tmp
COPY ./build /tmp/build
RUN chmod -R +x /tmp/build

RUN source /tmp/build/scriptenv.sh
#ENV PYTHONV $(python3 -c "exec(\"import sys\nprint(f'{sys.version_info.major}.{sys.version_info.minor}')\")")
#RUN python3 /tmp/build/setenv.py

RUN echo $PYTHONV

With scriptenv.sh being:

export PYTHONV=$(python3 -c "exec(\"import sys\nprint(f'{sys.version_info.major}.{sys.version_info.minor}')\")")

Yet it outputs a blank string.

For reference, this is what the string outputs:

user@user-VirtualBox:~$ python3 -c "exec(\"import sys\nprint(f'{sys.version_info.major}.{sys.version_info.minor}')\")"
3.8

I cannot specify the environment variable before. It has to be during runtime since its based on “atlassian/default-image:3” and the Python version could change.

I need to get the Python version so I can install the correct packages.

What can I do?

Define the variable and run the install in one RUN instruction. This is probably the only way. Or maybe using mount feature of buildkit and use a shared folder for each temporary build container. But the other is easier. Everything you write after the RUN keyword will run in a container. When the command terminates, the container stops. Even if it ran, you could not read an environment variable existing in an other container.

The ENV instruction will not let you dinamically set a variable based on a command. It is just a key-value pair.

1 Like

Yup, that seemed to be the obvious & easiest solution. Thank you so much!