Tarun Chawla
Tarun Chawla

Reputation: 351

Dockerfile ENV variable substitution into another ENV variable

I am learning Docker and facing issue in substituting the value of one env variable into another env variable.

This is my Dockerfile

FROM ubuntu

ENV var_env=Tarun

ENV command="echo Hello $var_env"

CMD ["sh","-c","echo Hello $var_env"]

Now, after building it with tag name "exp", then

sudo docker run -e  "var_env=New Env Value" exp

It gives me correct output as

Hello New Env Value

But, if I see the environment variables associated by executing

sudo docker run -e  "var_env=New Env Value" exp env

It gives me this output:

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=138aa8852d8d
var_env=New Env Value
command=echo Hello Tarun
HOME=/root

In it, the value of var_env environment variable is changed and value of command environment variable remains same.

I need to find a way so that if I change the value of var_env environment variable by the above command, it will update the value of var_env environment variable inside command environment variable also.

For reference: https://docs.docker.com/engine/reference/builder/#environment-replacement

Upvotes: 16

Views: 17675

Answers (1)

ckaserer
ckaserer

Reputation: 5742

Option 1: at container start

You can use a wrapper script to create your environment variables with the inheritance that you wish. Here is a simple wrapper script

wrapper.sh

#!/bin/bash

# prep your environement variables
export command="echo Hello $var_env"

# run your actual command
echo "Hello $command"

Your dockerfile needs to be adapted to use it

FROM ubuntu
COPY ./wrapper.sh .
ENV var_env=Tarun
ENV command="echo Hello $var_env"
CMD ["sh","-c","./wrapper.sh"]

Option 2: during build

You can archive this by rebuilding your image with different build args. Lets keep your dockerfile almost the same:

FROM ubuntu
ARG var_env=Tarun
ENV command="echo Hello $var_env"
CMD ["sh","-c","echo Hello $var_env"]

and run

docker build -t test .

this gives you your default image as defined in your dockerfile, but your var_env is no longer an environment variable.

next we run

docker build -t test --build-arg var_env="New Env Value" .

this will invalidate the docker cache only from the line in which you have defined your build arg. So keep your definition of your ARG close to where it is used in order to maximize the caching functionality of docker build.

You can find more about build args here: https://docs.docker.com/engine/reference/commandline/build/

Upvotes: 6

Related Questions