skip to Main Content

I have a bit of a weird situation where I need to source the output of a script to set up some environment variables (which are only known at build time) before several RUN steps in my Dockerfile.

I know I can do this:

SHELL ["/bin/bash", "-c"] 
RUN source <(./my_script) && echo "step 1"
RUN source <(./my_script) && echo "step 1"

And so on. But is there any way I can avoid repeating the source for every step?

2

Answers


  1. You may be able to avoid this with ARG and ENV, running the script in the host env

    ARG VALUE_A="${VALUE_A}"
    ENV VALUE_A=$VALUE_A
    

    More details at How do I copy variables between stages of multi stage Docker build?

    Otherwise you run into https://github.com/moby/moby/issues/29110 (from Answer to Dockerfile – set ENV to result of command)


    For completeness, it possible to hack around many limitations of Dockerfiles by providing your container access to the docker daemon

    While this sounds neat, and allows you to go so far as to execute an arbitrary script which results in a new, dynamic Dockerfile which you can immediately run .. I don’t and can’t possibly recommend this route in vanilla docker due to all of its maintainabiltiy and security flaws

    Details warnings here about doing this without compose and buildkit (also requires host/OS changes) Access docker within Dockerfile?

    A similar procedure is much safer and borderline useful with docker compose and buildkit (in such a context, you can provide access to the docker socket!), but still not generally recommendable.. still, going with docker compose can give you more useful tools in general to provide env values, but is not always possible

    Login or Signup to reply.
  2. Create a script named my_source with following content :

    unset BASH_ENV
    source <(./my_script)
    

    Then in you Dockerfile :

    SHELL ["/bin/bash", "-c"]
    ENV BASH_ENV "./my_source"
    
    COPY my_script my_source ./
    
    RUN echo "$VAR_DEFINED_IN_my_script"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search