Skip to content

Instantly share code, notes, and snippets.

@marlluslustosa
Created June 28, 2023 16:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marlluslustosa/0240f89e2d8ffa14c23ca77fcbda39a3 to your computer and use it in GitHub Desktop.
Save marlluslustosa/0240f89e2d8ffa14c23ca77fcbda39a3 to your computer and use it in GitHub Desktop.
Pass VARS in secrets to ENV service stack swarm
#!/bin/sh
#
# Marllus Lustosa
# Ref: https://gist.github.com/devfelipereis/c31dba17bf48150137761097c4c6637f
#
# Script for loading environment variables from secret files (Swarm secrets)
#
# This script allows loading environment variables from secret files,
# providing a secure way to store sensitive information such as passwords or
# API keys, separate from source code or configuration files.
#
# By calling this script through entrypoint.sh, all variables within the secret file
# will be passed to the local shell of the container, and the application can read them.
#
# Advantages of this approach: Encryption of the secrets file, possibility to set permissions
# at the group level of Portainer (and for which stacks it will be available),
# advantage of the variables not appearing in the container's ENV list, which reduces the
# exposure surface of sensitive content.
#
# To define a secrets file in Portainer, go to (https://docs.portainer.io/user/docker/secrets/add).
# In the example below, the file 'secrets-env-app' is defined and variables are added in this format:
# DB_HOST=mariadb
# DB_DATABASE=mydatabase
# DB_USERNAME=superuser
# DB_PASSWORD=supersecretpassword
#
# Then, in the stack description, you just need to define:
#
# services:
# exemplo-env:
# image: image-php8-adapted
# environment:
# - SECRET_NAME=secrets-env-app
# secrets:
# - secrets-env-app
#
# secrets:
# secrets-env-app:
# external: true
#
# When you run the stack, all the variables will be set in the shell of the target service.
# Default directory for secrets
ENV_SECRETS_DIR=${ENV_SECRETS_DIR:-/run/secrets}
# Function to display debug messages, if the ENV_SECRETS_DEBUG variable is set
env_secret_debug() {
if [ -n "$ENV_SECRETS_DEBUG" ]; then
echo "$@"
fi
}
# Function to load environment variables from the secret file
set_env_secrets() {
local secret_name="$SECRET_NAME"
local 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_name"
fi
if [ -n "$ENV_SECRETS_DEBUG" ]; then
echo -e "\nExpanded environment variables"
printenv
fi
}
# Call the function to load environment variables
set_env_secrets
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment