DevOps Scripting PatternsLesson 6.2
Managing secrets and environment variables in Bash
never hardcode secrets, environment variable injection, .env file loading, printenv and env auditing, secret masking in logs, vault and AWS SSM integration patterns, secure temporary files, variable sanitization
Secrets Don't Belong in Scripts
Hardcoded secrets in scripts end up in git history. The right pattern: inject via environment or a secret manager at runtime.
# BAD โ never do this
DB_PASSWORD="super_secret_123"
# GOOD โ read from environment
DB_PASSWORD="${DB_PASSWORD:?DB_PASSWORD must be set}"
# Load from .env file (development only)
if [[ -f ".env" ]]; then
set -a # auto-export all variables
# shellcheck disable=SC1091
source .env
set +a
fiMasking Secrets in Logs
log_safe() {
local message="$1"
# Mask anything that looks like a secret
local sanitized
sanitized=$(echo "$message" | sed 's/=[^[:space:]]*/=***/g')
echo "[$(date +%T)] $sanitized"
}
# Never print the value of secret variables
log_safe "Connecting with API_KEY=$API_KEY" # BAD
log_safe "Connecting to API" # GOODAWS SSM Parameter Store
get_secret() {
local param_name="$1"
aws ssm get-parameter \
--name "$param_name" \
--with-decryption \
--query 'Parameter.Value' \
--output text
}
DB_PASSWORD=$(get_secret "/prod/myapp/db-password")
export DB_PASSWORDTreat set -x output as a security risk โ it prints every command including variable values. Disable tracing around secret-handling code with set +x.
