Ryan Kostrzewa
Ryan Kostrzewa

Reputation: 15

Can I pass a *reference* to an environment variable in a docker CMD?

I running a docker container through an ECS task, and attempting to override the Docker CMD in the Task Definition. I do not have control over the docker container, but by default it has an entrypoint of "/share/script.sh".

This entrypoint script, ultimately, invokes Chef Inspec (a compliance checking application) with arguments passed in from $@, like this:

inspec exec linux-baseline $@

When I pass in plaintext arguments by overriding CMD, everything is great. For example, passing in

CMD ["--backend","ssh"]

will result in

inspec exec linux-baseline --backend ssh

being executed.

What I would like to do is pass in a reference to a container environment variable via CMD (let's assume we know it's defined that $STACK=stack-name) - something like:

CMD ["--stack","${STACK}"]

where the executed code would be

inspec exec linux-baseline --stack stack-name

Is there any way to do this?

Upvotes: 0

Views: 677

Answers (1)

David Maze
David Maze

Reputation: 158917

The best way might be to move this option into your startup script. You can't do this with only CMD syntax.

If you're willing to part with the container-as-command pattern, you can achieve this by not having an ENTRYPOINT and using the string form of CMD:

# Reset ENTRYPOINT to empty
ENTRYPOINT []
CMD /share/script.sh --stack "${STACK}"

This also means you would need to include the script name if you override CMD in a docker run invocation or a Compose command:.

A similar option is to write your own wrapper script to be the new entrypoint that potentially fills in more options:

#!/bin/sh
exec /share/script.sh --stack "${STACK}" "$@"
ENTRYPOINT ["/new-entrypoint.sh"]

Docker never does environment variable expansion natively here. Instead, the CMD directive has two forms:

  1. If you use a JSON array CMD ["--stack", "${STACK}"] there is no interpolation or other processing; the command part is exactly the two words --stack {STACK}.
  2. If you use anything else, Docker injects a shell to run the command, and that shell can do environment variable expansion; the command part is exactly the three words sh, -c, and the command string as a single word (quotes, punctuation, braces, and all).

In your case you can't use either form: the first form doesn't do the variable expansion, and the second form includes words sh and -c that your script won't understand.

Upvotes: 1

Related Questions