Reputation: 9267
At work we are able to build image from Dockerfile and we do not have access to the docker command.
My goal is to be able to set environment variables based on my commit message or branch. Here is my try:
RUN branch=$(git branch | sed -n -e 's/^\* \(.*\)/\1/p' | awk -Frelease/ '/release/{print $2}') \
&& if [[ "$branch" != qa* ]]; then branch=$(git log -1 --pretty | grep release\/ | awk -Frelease/ '/release/{print $2}' | awk -F: '{print $1}'); fi
ENV EXPORT_ENV $branch
CMD ["npm", "run", "start"]
However, in my npm run start
script it gets process.env.EXPORT_ENV
as undefined
.
Upvotes: 1
Views: 1294
Reputation: 312610
On second thought, let me expand on my comment:
You can't set Dockerfile environment variables to the result of commands in a RUN statement. Variables set in a RUN statement are ephemeral; they exist only while the RUN statement is active
If you don't have access to the host environment (to pass arguments to the docker build
command), you're not going to be able to do exactly what you want.
However, you can add an ENTRYPOINT
script to your container that will set up dynamic environment variables before the main process runs. That is, if you have in your Dockerfile
:
ENTRYPOINT ["/docker-entrypoint.sh"]
And in /docker-entrypoint.sh
you have:
#!/bin/bash
branch=$(git branch | sed -n -e 's/^\* \(.*\)/\1/p' | awk -Frelease/ '/release/{print $2}') \
&& if [[ "$branch" != qa* ]]; then branch=$(git log -1 --pretty | grep release\/ | awk -Frelease/ '/release/{print $2}' | awk -F: '{print $1}'); fi)
export EXPORT_ENV="$branch"
exec "$@"
Then the EXPORT_ENV
environment variable would be available in the environment of your CMD
process.
Upvotes: 2