2

I am running a docker exec -it ... command and I need to use an environment variable of my docker container. An example:

docker exec -it container_id command_here param_1 $param_2_as_env_variable

In the case above, it pulls param_2_as_env_variable from host machine, and not the docker container. Is it possible to use env variable from container itself while running docker exec ... command from another machine?


Update: I can use ouput of docker exec -it container_id printenv | grep .... But I couldn't separate value and key. How can I get only value here?

2 Answers 2

4

Something like this could work (it assumes, the container has a shell installed)

docker exec -it container_id sh -c 'command_here param_1 $param_2_as_env_variable'

For example the following works:

docker exec -it test sh -c 'echo $HOSTNAME'

to give the host name of the container.

Sign up to request clarification or add additional context in comments.

4 Comments

Nope, this still gets host machine's env variable.
Now it accepts as a plain string. Doesn't parse at all :(
Are you sure the environment variable is defined in the container?
Yes, I can see it when I run printenv. I updated the question, can you check?
3

You need to escape the variable to pass it to the docker exec command unresolved:

Try:

docker exec -it container_id command_here param_1 \$param_2_as_env_variable

3 Comments

This produces illegal input exception. So it doesn't parse $param2 at all, it just gets it as plain string.
This produces illegal input exception. So it doesn't parse How does "illegal input exception" (what does "produce" the message exactly? What is the message exactly?) lead to "doesn't parse"?
Sorry, the error wasn't related this case. The answer is correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.