50 lines
1.8 KiB
Bash
50 lines
1.8 KiB
Bash
|
|
#!/usr/bin/env bash
|
||
|
|
# =============================================================================
|
||
|
|
# Replaces every "change-me..." placeholder in .env with a freshly generated
|
||
|
|
# secret.
|
||
|
|
#
|
||
|
|
# config/settings/prod.py refuses to start on a placeholder value, so this is
|
||
|
|
# what makes the very first `make up` both work and be safe: nobody ends up
|
||
|
|
# running a real deployment on the credentials published in .env.example.
|
||
|
|
#
|
||
|
|
# scripts/generate_secrets.sh [path-to-env] (default: .env)
|
||
|
|
#
|
||
|
|
# Only placeholders are touched - a value you have already set is left alone,
|
||
|
|
# so re-running this is safe and never invalidates working credentials.
|
||
|
|
# =============================================================================
|
||
|
|
set -Eeuo pipefail
|
||
|
|
|
||
|
|
ENV_FILE="${1:-.env}"
|
||
|
|
|
||
|
|
[[ -f "${ENV_FILE}" ]] || { echo "No ${ENV_FILE} to update." >&2; exit 1; }
|
||
|
|
|
||
|
|
# `openssl rand -base64` is available anywhere Docker is; tr strips the
|
||
|
|
# characters that would need quoting inside a URL-shaped DATABASE_URL.
|
||
|
|
random() { openssl rand -base64 48 | tr -d '\n=+/' | cut -c1-"${1:-50}"; }
|
||
|
|
|
||
|
|
changed=0
|
||
|
|
for key in DJANGO_SECRET_KEY POSTGRES_PASSWORD ELASTIC_PASSWORD; do
|
||
|
|
current="$(grep -E "^${key}=" "${ENV_FILE}" | head -1 | cut -d= -f2- || true)"
|
||
|
|
|
||
|
|
case "${current,,}" in
|
||
|
|
*change-me*|*changeme*|'')
|
||
|
|
# 64 chars for the signing key (prod.py enforces >= 50), 32 for the
|
||
|
|
# service passwords.
|
||
|
|
length=32
|
||
|
|
[[ "${key}" == "DJANGO_SECRET_KEY" ]] && length=64
|
||
|
|
value="$(random "${length}")"
|
||
|
|
# `|` as the sed delimiter: generated values never contain it.
|
||
|
|
sed -i "s|^${key}=.*|${key}=${value}|" "${ENV_FILE}"
|
||
|
|
echo " generated ${key}"
|
||
|
|
changed=1
|
||
|
|
;;
|
||
|
|
*)
|
||
|
|
echo " kept ${key} (already set)"
|
||
|
|
;;
|
||
|
|
esac
|
||
|
|
done
|
||
|
|
|
||
|
|
if [[ "${changed}" -eq 1 ]]; then
|
||
|
|
echo "Secrets written to ${ENV_FILE}. It is gitignored - back it up somewhere safe."
|
||
|
|
fi
|