Sample script that allows you to define as environment variables the name of the docker secret that contains the secret value. It will be in charge of analyze all the environment variables searching for the placeholder to substitute the variable value by the secret.
You can define the next environment variables:
$ env | grep DB_
DB_HOST=my-db-host
DB_USER=my-db-user
DB_PASS=my-db-pass
And nothing would happen. None of the variables would be modified when starting the container.
But if you define variables with the defined placeholder it will expand the value with the referred secret.
Create Secret
echo "my-db-pass" | docker secret create secret-db-pass -
$ env | grep DB_
DB_HOST=my-db-host
DB_USER=my-db-user
DB_PASS={{DOCKER-SECRET:secret-db-pass}}
When starting the script will search for the placeholder {{DOCKER-SECRET:xxxx}}
on each
environment variable and will substitute the value by the content of the secret xxxx
,
in this example it means to end up with:
DB_HOST=my-db-host
DB_USER=my-db-user
DB_PASS=my-db-pass
If you want to use this feature on any image just add the env_secrets_expand.sh
file in your container entrypoint script and invoke it with source env_secrets_expand.sh
Build a sample image with the required dependency and enter into it:
docker run --rm -v $PWD:/test -it alpine sh
Just emulate the creation of a secret and the example variables with the next commands:
mkdir -p /run/secrets/
echo "my-db-pass" > /run/secrets/secret-db-pass
export DB_HOST=my-db-host
export DB_USER=my-db-user
export DB_PASS={{DOCKER-SECRET:secret-db-pass}}
Execute the script:
ENV_SECRETS_DEBUG=true /test/env_secrets_expand.sh
I changed mine.
https://gist.github.com/devfelipereis/c31dba17bf48150137761097c4c6637f
Mine will work a little bit different... For example, I have a lot of laravel apps and I have a .env like this:
I don't want to create a secret for each field and I don't want to write {{DOCKER-SECRET:secret-db-pass}} in my compose files.
I want all this in one secret... one secret for each application.
What I did, I changed the code to read a secret file and set each line as a env variable... and it works!
All I need to do is:
Your application will read the env as usual and you don't need to define the env in your compose files.. Of course, you can still set stuff that don't need to be secret... like APP_ENV=production in your compose.
I'm using with Rancher to deploy my apps and it works good 👍