Script Valley
Bash Scripting for Developers
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

Secret injection and masking pattern

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
fi

Masking 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"                 # GOOD

AWS 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_PASSWORD

Treat set -x output as a security risk โ€” it prints every command including variable values. Disable tracing around secret-handling code with set +x.

Up next

Building a CI/CD deployment script in Bash

Sign in to track progress

Managing secrets and environment variables in Bash โ€” DevOps Scripting Patterns โ€” Bash Scripting for Developers โ€” Script Valley โ€” Script Valley