fledgling
fledgling

Reputation: 1051

Export environment variables inside docker container

I am trying to run a shell script env_var.sh inside the docker container. The contents of the script is shown below. What its essentially trying is getting the access keys from a specific profile

echo "# Environment for AWS profile dev"

echo export AWS_PROFILE=dev
echo export AWS_ACCESS_KEY_ID=(aws configure get aws_access_key_id --profile dev)
echo export AWS_SECRET_ACCESS_KEY=(aws configure get aws_secret_access_key --profile dev)
echo export AWS_DEFAULT_REGION=(aws configure get region --profile dev)

echo "dev environment variables exported"

and this is my dockerfile

FROM docker:17.04.0-ce

RUN apk update && apk add python && apk add py-pip && apk add bash

RUN pip install pip --upgrade && pip install setuptools --upgrade && pip install awscli && pip install cfdeployment==0.2.3 --extra-index-url https://dn2h7gel4xith.cloudfront.net

VOLUME /tmp/work
VOLUME /root/.aws

ADD test.sh /root/test.sh
ADD aws_env.sh /root/env_var.sh
ADD config /root/.aws/config
ADD credentials /root/.aws/credentials

RUN /root/env_var.sh


ENTRYPOINT ["/root/test.sh", "cfdeployment"]
CMD ["--version"]

The output for RUN /root/env_var.shI am seeing is as below. I don't see access key substituted from the role. Any idea what might be happening

Step 9/11 : RUN /root/aws_env.sh
 ---> Running in ca46f4c516eb
# Environment for AWS profile ''
export AWS_PROFILE=dev
export AWS_ACCESS_KEY_ID=
export AWS_SECRET_ACCESS_KEY=
export AWS_DEFAULT_REGION=

dev environment variables exported

or is there a different way to set these env variables which picks up the keys from from he profile using docker run command?

Upvotes: 6

Views: 19579

Answers (2)

Adriano Lima
Adriano Lima

Reputation: 71

You can use ENV in your dockerfile to create these variables, setting them individually, e.g.:

ENV AWS_PROFILE=dev

There is another command called ARG, which you can use to set variables that need to be available only on build stage.

Upvotes: 7

bhb603
bhb603

Reputation: 481

Firstly, I think the reason env_var.sh isn't working is because it's missing dollar signs, $( ) ... should be like this:

echo export AWS_ACCESS_KEY_ID=$(aws configure get aws_access_key_id --profile dev)

But regardless of that, the better way to supply environment variables to docker containers is at run time, not baking them into the image. This way the image is de-coupled from configuration... you can change the environment variables w/out re-building, and you can remove all that mess in the Dockerfile where you're copying your local aws configuration into the image. So you would use the docker run -e option:

docker run -e AWS_PROFILE=dev -e "AWS_ACCESS_KEY_ID=$(aws configure get aws_access_key_id --profile dev)" my-image

See https://docs.docker.com/engine/reference/commandline/run/#set-environment-variables--e---env---env-file

Upvotes: 7

Related Questions