80 lines
2.2 KiB
Bash
Executable File
80 lines
2.2 KiB
Bash
Executable File
#!/usr/bin/env bash
|
|
set -euo pipefail
|
|
|
|
REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
|
VAULT_FILE="${VAULT_FILE:-$REPO_DIR/secrets/vault.yml}"
|
|
VAULT_PASS_FILE="${VAULT_PASS_FILE:-$HOME/.config/vault-pass.txt}"
|
|
|
|
usage() {
|
|
cat <<EOF
|
|
用法:
|
|
scripts/vault.sh init 初始化 vault password file(若不存在)
|
|
scripts/vault.sh view 檢視加密檔內容
|
|
scripts/vault.sh edit 編輯加密檔內容
|
|
scripts/vault.sh encrypt FILE 將檔案加密成 ansible-vault 格式
|
|
scripts/vault.sh decrypt OUT 解密到指定輸出檔
|
|
scripts/vault.sh rekey 重新加密並更新 key
|
|
EOF
|
|
}
|
|
|
|
ensure_pass() {
|
|
mkdir -p "$(dirname "$VAULT_PASS_FILE")"
|
|
chmod 700 "$(dirname "$VAULT_PASS_FILE")" || true
|
|
if [ ! -f "$VAULT_PASS_FILE" ]; then
|
|
umask 177
|
|
python3 - <<'PY' > "$VAULT_PASS_FILE"
|
|
import secrets
|
|
print(secrets.token_urlsafe(48))
|
|
PY
|
|
chmod 600 "$VAULT_PASS_FILE"
|
|
echo "已建立 vault password file: $VAULT_PASS_FILE"
|
|
fi
|
|
}
|
|
|
|
cmd="${1:-}"
|
|
case "$cmd" in
|
|
init)
|
|
ensure_pass
|
|
;;
|
|
view)
|
|
ensure_pass
|
|
ansible-vault view "$VAULT_FILE" --vault-password-file "$VAULT_PASS_FILE"
|
|
;;
|
|
edit)
|
|
ensure_pass
|
|
[ -f "$VAULT_FILE" ] || { echo "找不到 $VAULT_FILE"; exit 1; }
|
|
ansible-vault edit "$VAULT_FILE" --vault-password-file "$VAULT_PASS_FILE"
|
|
;;
|
|
encrypt)
|
|
ensure_pass
|
|
src="${2:-}"
|
|
[ -n "$src" ] || { usage; exit 1; }
|
|
cp "$src" "$VAULT_FILE"
|
|
ansible-vault encrypt "$VAULT_FILE" --vault-password-file "$VAULT_PASS_FILE"
|
|
;;
|
|
decrypt)
|
|
ensure_pass
|
|
out="${2:-}"
|
|
[ -n "$out" ] || { usage; exit 1; }
|
|
ansible-vault decrypt "$VAULT_FILE" --output "$out" --vault-password-file "$VAULT_PASS_FILE"
|
|
chmod 600 "$out" || true
|
|
;;
|
|
rekey)
|
|
ensure_pass
|
|
tmp_new="$(mktemp)"
|
|
chmod 600 "$tmp_new"
|
|
python3 - <<'PY' > "$tmp_new"
|
|
import secrets
|
|
print(secrets.token_urlsafe(48))
|
|
PY
|
|
ansible-vault rekey "$VAULT_FILE" --vault-password-file "$VAULT_PASS_FILE" --new-vault-password-file "$tmp_new"
|
|
mv "$tmp_new" "$VAULT_PASS_FILE"
|
|
chmod 600 "$VAULT_PASS_FILE"
|
|
echo "已更新 vault key: $VAULT_PASS_FILE"
|
|
;;
|
|
*)
|
|
usage
|
|
exit 1
|
|
;;
|
|
esac
|