Skip to content

Instantly share code, notes, and snippets.

@hsandrade
Forked from devfelipereis/README.md
Created April 6, 2018 02:37
Show Gist options
  • Save hsandrade/8cb812e74d808ff07f3d5bf084047530 to your computer and use it in GitHub Desktop.
Save hsandrade/8cb812e74d808ff07f3d5bf084047530 to your computer and use it in GitHub Desktop.
Docker Env Vars expanded with secrets content

Set secrets as env variables in docker

This script will read your secret file and set each line as an env variable in your container.

How to use it

I' assuming that you already has a entrypoint file in your Dockerfile. So now, you need to copy and paste the contents of set_env_secrets.sh to your entrypoint(you don't need the first line).

Now, you need to create a secret, the name could be whatever you like. I'm using the name of my application as a pattern for my secrets name. For this example, my secret name will be super-project and the content will be.

DB_HOST=mariadb
DB_DATABASE=mydatabase
DB_USERNAME=superuser
DB_PASSWORD=supersecretpassword

Then, in my compose file, I need to set that secret name. Like this:

application:
    image: IMAGENAME
    secrets:
      - super-project
    labels:
      - io.rancher.container.pull_image=always
    environment:
      **SECRET_NAME:super-project**

Now you just need to deploy your app and each line of that secret file will be a env variable for your application.

#!/bin/sh
: ${ENV_SECRETS_DIR:=/run/secrets}
env_secret_debug()
{
if [ ! -z "$ENV_SECRETS_DEBUG" ]; then
echo -e "\033[1m$@\033[0m"
fi
}
set_env_secrets() {
secret_name=$SECRET_NAME
secret_file_path="${ENV_SECRETS_DIR}/${secret_name}"
env_secret_debug "Secret file: $secret_name"
if [ -f "$secret_file_path" ]; then
while IFS='' read -r line || [[ -n "$line" ]]; do
export $line
done < "$secret_file_path"
else
env_secret_debug "Secret file does not exist! $secret"
fi
if [ ! -z "$ENV_SECRETS_DEBUG" ]; then
echo -e "\n\033[1mExpanded environment variables\033[0m"
printenv
fi
}
set_env_secrets
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment