infra/scripts/state-sync
Viktor Barzin 4e7ca1ad61 state: add Vault Transit as primary SOPS backend, age as fallback
- .sops.yaml: add hc_vault_transit_uri for transit/keys/sops-state
- state-sync: try Vault Transit first, fall back to age key on disk
- Re-encrypted all 101 state files with both Vault Transit + age
- Normal workflow: vault login → decrypt via Transit (no key files)
- Bootstrap/DR: age key at ~/.config/sops/age/keys.txt
2026-03-17 22:56:33 +00:00

79 lines
2.2 KiB
Bash
Executable file

#!/usr/bin/env bash
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
STATE_DIR="$REPO_ROOT/state/stacks"
VAULT_ADDR="${VAULT_ADDR:-https://vault.viktorbarzin.me}"
cmd="${1:-help}"
stack="${2:-}" # optional: operate on single stack
# Check if Vault token is valid
vault_available() {
VAULT_ADDR="$VAULT_ADDR" vault token lookup &>/dev/null 2>&1
}
encrypt_state() {
local dir="$1"
local src="$dir/terraform.tfstate"
local dst="$dir/terraform.tfstate.enc"
[ -f "$src" ] || return 0
# Only re-encrypt if state is newer than encrypted version
if [ ! -f "$dst" ] || [ "$src" -nt "$dst" ]; then
sops -e --input-type json --output-type json "$src" > "$dst"
fi
}
decrypt_state() {
local dir="$1"
local src="$dir/terraform.tfstate.enc"
local dst="$dir/terraform.tfstate"
[ -f "$src" ] || return 0
if vault_available; then
# Vault Transit — no local key needed
sops -d --input-type json --output-type json "$src" > "$dst"
elif [ -f "${SOPS_AGE_KEY_FILE:-$HOME/.config/sops/age/keys.txt}" ]; then
# Fallback: age key on disk (bootstrap / Vault down)
echo "state-sync: Vault unavailable, falling back to age key" >&2
SOPS_AGE_KEY_FILE="${SOPS_AGE_KEY_FILE:-$HOME/.config/sops/age/keys.txt}" \
sops -d --input-type json --output-type json "$src" > "$dst"
else
echo "state-sync: ERROR — no Vault token and no age key at ~/.config/sops/age/keys.txt" >&2
return 1
fi
}
case "$cmd" in
encrypt)
if [ -n "$stack" ]; then
encrypt_state "$STATE_DIR/$stack"
else
for dir in "$STATE_DIR"/*/; do
encrypt_state "$dir"
done
fi
;;
decrypt)
if [ -n "$stack" ]; then
decrypt_state "$STATE_DIR/$stack"
else
for dir in "$STATE_DIR"/*/; do
decrypt_state "$dir"
done
fi
;;
commit)
# Encrypt all changed state, then git add + commit
"$0" encrypt
cd "$REPO_ROOT"
git add state/stacks/*/terraform.tfstate.enc
if ! git diff --cached --quiet; then
git commit -m "state: update encrypted terraform state"
fi
;;
help)
echo "Usage: state-sync {encrypt|decrypt|commit} [stack-name]"
echo "Decrypt uses Vault Transit if logged in, falls back to age key."
;;
esac