1

I'm trying to create dockerfile similar to the following one:

FROM python:3.8-slim-buster
ENV FOO=bar
RUN python my_python_file.py  # use the FOO variable, and set PY_VERSION variable

FROM python:<PY_VERSION>-slim-buster
# continue dockerfile...
  1. How can I use the FOO variable from within my python my_python_file script?
    (I think I can pass FOO as an argument to the RUN python my_python_file.py command, and read the argument from within the my_python_file.py file. I wonder if there's an easier way, something that maybe using os.getenv('FOO'))
  2. How can I set PY_VERSION from within my python my_python_file script, to later be used by the 2nd FROM command - FROM python:<PY_VERSION>-slim-buster?

I dont have any control over how the docker build command is being executed.

Kaneki21
  • 1,323
  • 2
  • 4
  • 22
asafal
  • 43
  • 4
  • 1
    for 1. you can do just that, however I would use ARG instead of ENV. for 2. it cannot be done. that's a logic that is better implemented outside Dockerfile – Mihai Sep 18 '22 at 11:19
  • Thanks @Mihai. Regarding 2. why it's not possible? I guess it's because there is no way for a python script to set a dockerfile ENV / ARG variables at `build` runtime? – asafal Sep 18 '22 at 12:15
  • 1
    because docker was not built for such a workflow – Mihai Sep 18 '22 at 12:16

1 Answers1

2

How can I use the FOO variable from within my python my_python_file script?

Read it from environment variables.

omething that maybe using os.getenv('FOO'))

How do I access environment variables in Python?

How can I set PY_VERSION from within my python my_python_file script, to later be used by the 2nd FROM command - FROM python:<PY_VERSION>-slim-buster?

That is not possible.

Dynamically get/set dockerfile variables

Generate the Dockerfile file from a wrapper script.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111