#!/usr/bin/env bash # # update-env.sh # Reusable .env update/migration script. # # Reads a template file (default: .env.template) and merges it with an # existing .env file (default: .env), then writes the result. # # Rules: # 1. Template keys with a concrete value -> template wins (replaces old value). # 2. Template keys with an empty value -> taken over from existing .env. # 3. Template keys with $(openssl rand...) -> existing value kept if present, # otherwise the command is executed. # 4. Keys only in existing .env -> preserved (appended at bottom), # unless --drop-unknown is passed. # # A diff report is always printed before writing. # # Usage: # ./update-env.sh [existing.env] [template.env] [output.env] [options] # # Defaults: # existing.env = .env # template.env = .env.template # output.env = same as existing.env # # Options: # -n, --dry-run Print result to stdout, write nothing. # --force-regen-secrets Always re-execute rand commands (discard existing). # --drop-unknown Do not carry over keys only in the existing .env. # -h, --help Show help. # # Idempotent: safe to re-run; won't re-roll secrets on subsequent runs. # set -euo pipefail # ================================================================ logging if [[ -t 1 ]]; then C_R=$'\033[31m'; C_G=$'\033[32m'; C_Y=$'\033[33m'; C_B=$'\033[1m'; C_0=$'\033[0m' else C_R=""; C_G=""; C_Y=""; C_B=""; C_0=""; fi ok() { printf '%s%s%s\n' "$C_G" "$*" "$C_0"; } warn() { printf '%s[warn] %s%s\n' "$C_Y" "$*" "$C_0" >&2; } die() { printf '%s[error] %s%s\n' "$C_R" "$*" "$C_0" >&2; exit 1; } log() { printf '%s\n' "$*"; } hd() { printf '\n%s━━━ %s ━━━%s\n' "$C_B" "$*" "$C_0"; } sec() { printf ' %s%s%s\n' "$C_B" "$*" "$C_0"; } usage() { cat <<'USAGE' Usage: update-env.sh [existing.env] [template.env] [output.env] [options] existing.env current .env to inherit values from (default: .env) template.env desired structure / new values (default: .env.template) output.env file to write the merged result (default: same as existing) Options: -n, --dry-run Print merged result to stdout, write nothing. --force-regen-secrets Re-execute all rand commands (discard existing secrets). --drop-unknown Do not preserve keys that only exist in the old .env. -h, --help Show this help. USAGE } # ================================================================ args DRY_RUN=0; FORCE_REGEN=0; DROP_UNKNOWN=0 INPUT_ENV=""; TEMPLATE_ENV=""; OUTPUT_ENV="" while [[ $# -gt 0 ]]; do case "$1" in -n|--dry-run) DRY_RUN=1 ;; --force-regen-secrets) FORCE_REGEN=1 ;; --drop-unknown) DROP_UNKNOWN=1 ;; -h|--help) usage; exit 0 ;; -*) die "Unknown option: $1 (see --help)" ;; *) if [[ -z "$INPUT_ENV" ]]; then INPUT_ENV="$1" elif [[ -z "$TEMPLATE_ENV" ]]; then TEMPLATE_ENV="$1" elif [[ -z "$OUTPUT_ENV" ]]; then OUTPUT_ENV="$1" else die "Too many positional arguments."; fi ;; esac shift done [[ -n "$INPUT_ENV" ]] || INPUT_ENV=".env" [[ -n "$TEMPLATE_ENV" ]] || TEMPLATE_ENV=".env.template" [[ -n "$OUTPUT_ENV" ]] || OUTPUT_ENV="$INPUT_ENV" # ================================================================ preflight command -v openssl >/dev/null 2>&1 || die "openssl is required but not found." [[ -f "$TEMPLATE_ENV" ]] || die "Template file not found: $TEMPLATE_ENV" if [[ ! -f "$INPUT_ENV" ]]; then warn "Existing env '$INPUT_ENV' not found — all empty/secret values will be fresh." fi # ================================================================ helpers trim() { local s="$1" s="${s#"${s%%[![:space:]]*}"}" s="${s%"${s##*[![:space:]]}"}" printf '%s' "$s" } # split RHS -> _val (trimmed core) + _cmt (optional trailing " # comment") split_rhs() { local rhs="$1" _val=""; _cmt="" if [[ "$rhs" =~ ^([^#]+)([[:space:]]+#.*)$ ]]; then _val="${BASH_REMATCH[1]}"; _cmt="${BASH_REMATCH[2]}" else _val="$rhs" fi _val="$(trim "$_val")" } # ================================================================ load existing .env declare -A OLD=() if [[ -f "$INPUT_ENV" ]]; then while IFS= read -r line || [[ -n "$line" ]]; do line="${line%$'\r'}" [[ -z "$(trim "$line")" ]] && continue [[ "$line" =~ ^[[:space:]]*# ]] && continue line="${line#export }" [[ "$line" != *"="* ]] && continue k="${line%%=*}"; v="${line#*=}" k="$(trim "$k")" split_rhs "$v"; v="$_val" # strip surrounding quotes if [[ ${#v} -ge 2 ]]; then if [[ "$v" == \"*\" ]]; then v="${v#\"}"; v="${v%\"}" elif [[ "$v" == \'*\' ]]; then v="${v#\'}"; v="${v%\'}"; fi fi OLD["$k"]="$v" done < "$INPUT_ENV" fi # ================================================================ merge declare -A TEMPLATE_KEYS=() # all keys defined in the template declare -A FINAL=() # key -> value actually written RESULT="" count_defined=0; count_inherited=0; count_generated=0 inherited_keys=(); generated_keys=(); overridden_keys=() rand_re='\$\(openssl[[:space:]]+rand[[:space:]]+-hex[[:space:]]+([0-9]+)\)' while IFS= read -r line || [[ -n "$line" ]]; do line="${line%$'\r'}" # pass through blanks / comments / non-KV lines as-is if [[ -z "$(trim "$line")" ]] || [[ "$line" =~ ^[[:space:]]*# ]] || [[ "$line" != *"="* ]]; then RESULT+="$line"$'\n' continue fi key="${line%%=*}"; rhs="${line#*=}" keytrim="$(trim "$key")" TEMPLATE_KEYS["$keytrim"]=1 split_rhs "$rhs"; val="$_val"; cmt="$_cmt" if [[ -z "$val" ]]; then # empty in template -> inherit from existing if [[ -n "${OLD[$keytrim]:-}" ]]; then newval="${OLD[$keytrim]}" count_inherited=$((count_inherited+1)) inherited_keys+=("$keytrim") else newval="" fi RESULT+="${key}=${newval}${cmt}"$'\n' FINAL["$keytrim"]="$newval" elif [[ "$val" =~ $rand_re ]]; then # $(openssl rand -hex N) placeholder hexlen="${BASH_REMATCH[1]}" if [[ -n "${OLD[$keytrim]:-}" && $FORCE_REGEN -eq 0 ]]; then newval="${OLD[$keytrim]}" count_inherited=$((count_inherited+1)) inherited_keys+=("$keytrim") else newval="$(openssl rand -hex "$hexlen")" count_generated=$((count_generated+1)) generated_keys+=("$keytrim") fi RESULT+="${key}=${newval}${cmt}"$'\n' FINAL["$keytrim"]="$newval" else # concrete value in template -> keep as-is (template wins) RESULT+="$line"$'\n' count_defined=$((count_defined+1)) FINAL["$keytrim"]="$val" # track overrides for the diff report if [[ -n "${OLD[$keytrim]:-}" && "${OLD[$keytrim]}" != "$val" ]]; then overridden_keys+=("$keytrim") fi fi done < "$TEMPLATE_ENV" # preserve keys only in the old .env unknown_extra="" unknown_count=0 if [[ $DROP_UNKNOWN -eq 0 && ${#OLD[@]} -gt 0 ]]; then while IFS= read -r k; do [[ -z "$k" ]] && continue if [[ -z "${TEMPLATE_KEYS[$k]:-}" && -n "${OLD[$k]:-}" ]]; then unknown_extra+="${k}=${OLD[$k]}"$'\n' unknown_count=$((unknown_count+1)) fi done < <(printf '%s\n' "${!OLD[@]}" | sort) fi if [[ -n "$unknown_extra" ]]; then RESULT+=$'\n'"# ── Preserved from existing .env (not in template) ──"$'\n' RESULT+="$unknown_extra" fi # ================================================================ DIFF REPORT hd "CHANGE REPORT: $INPUT_ENV -> $OUTPUT_ENV" # 1) Overridden: template has a different concrete value if [[ ${#overridden_keys[@]} -eq 0 ]]; then printf ' %s✔ no values overridden by template%s\n' "$C_G" "$C_0" else sec "Overridden by template (${#overridden_keys[@]}):" for k in "${overridden_keys[@]}"; do printf ' %s%s%s : %s -> %s\n' "$C_Y" "$k" "$C_0" "${OLD[$k]}" "${FINAL[$k]}" done fi # 2) Inherited: template was empty or rand, old value kept if [[ ${#inherited_keys[@]} -eq 0 ]]; then printf ' %s✔ no values inherited from existing .env%s\n' "$C_G" "$C_0" else sec "Inherited from existing .env (${#inherited_keys[@]}):" for k in "${inherited_keys[@]}"; do printf ' %s%s%s = %s\n' "$C_G" "$k" "$C_0" "${FINAL[$k]}" done fi # 3) Generated: fresh openssl rand if [[ ${#generated_keys[@]} -eq 0 ]]; then printf ' %s✔ no new secrets generated%s\n' "$C_G" "$C_0" else sec "Generated (openssl rand) (${#generated_keys[@]}):" for k in "${generated_keys[@]}"; do printf ' %s%s%s = %s…\n' "$C_R" "$k" "$C_0" "${FINAL[$k]:0:8}" done fi # 4) Additional keys (only in old .env) if [[ $unknown_count -eq 0 ]]; then printf ' %s✔ no additional keys in existing .env%s\n' "$C_G" "$C_0" else sec "Additional keys preserved (${unknown_count}):" while IFS= read -r k; do [[ -z "$k" ]] && continue if [[ -z "${TEMPLATE_KEYS[$k]:-}" && -n "${OLD[$k]:-}" ]]; then printf ' %s%s%s = %s\n' "$C_B" "$k" "$C_0" "${OLD[$k]}" fi done < <(printf '%s\n' "${!OLD[@]}" | sort) fi log "" # ================================================================ validate if grep -q 'openssl rand' <<< "$RESULT"; then die "A literal 'openssl rand' placeholder survived — substitution bug." fi for sk in USER_AUTH_SECRET ENCRYPTION_KEY_SECRET METRICS_AUTH_TOKEN OPENSEARCH_ADMIN_PASSWORD POSTGRES_PASSWORD; do if grep -qE "^[[:space:]]*${sk}=" <<< "$RESULT"; then lv="$(grep -E "^[[:space:]]*${sk}=" <<< "$RESULT" | head -1)" lv="$(trim "${lv#*=}")" [[ -z "$lv" ]] && warn "Secret '$sk' is EMPTY in the result." fi done # ================================================================ output if [[ $DRY_RUN -eq 1 ]]; then printf '%s' "$RESULT" log "(dry-run) nothing written." exit 0 fi # backup when overwriting in place if [[ -f "$INPUT_ENV" && "$INPUT_ENV" == "$OUTPUT_ENV" ]]; then bak="${INPUT_ENV}.bak.$(date +%Y%m%d-%H%M%S)" cp -p "$INPUT_ENV" "$bak" log "Backup -> $bak" fi mkdir -p "$(dirname "$OUTPUT_ENV")" tmp="$(mktemp)" printf '%s' "$RESULT" > "$tmp" mv "$tmp" "$OUTPUT_ENV" # ================================================================ summary hd "SUMMARY" printf ' Output : %s\n' "$OUTPUT_ENV" printf ' Template entries : %s\n' "${#TEMPLATE_KEYS[@]}" printf ' Kept from template: %s\n' "$count_defined" printf ' Inherited from old: %s\n' "$count_inherited" printf ' Generated (rand) : %s\n' "$count_generated" printf ' Overridden : %s\n' "${#overridden_keys[@]}" printf ' Extra keys kept : %s\n' "$unknown_count" if [[ -f "$INPUT_ENV" && "$INPUT_ENV" == "$OUTPUT_ENV" ]]; then printf ' Backup : %s.bak.*\n' "$INPUT_ENV" fi log "" ok "Done."