Last active
March 7, 2025 11:07
-
-
Save kristianheljas/d7cbfbed592e358fbf8b523486a119e8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
set -eu | |
#region Environment variables | |
: "${ANSIBLE_VAULT_PASSPHRASE:=}" | |
: "${ANSIBLE_VAULT_PASSPHRASE_FILE:=.vault-passphrase.gpg}" | |
: "${ANSIBLE_VAULT_PASSPHRASE_RECIPIENTS:=me@example.com}" | |
#endregion | |
#region Functions | |
log() { | |
local message="$1" | |
local severity="${2:-info}" | |
local code="${3:-1}" | |
echo "[$severity] $message" >&2 | |
if [ "$severity" = 'error' ]; then | |
exit "$code" | |
fi | |
} | |
generate_passphrase() { | |
gpg2 --gen-random --armor 2 128 | |
} | |
store_passphrase() { | |
passphrase_file="$1"; shift 1 | |
IFS=' ' read -ra recepients <<< "$@" | |
log "Writing passphrase to '$passphrase_file', gpg recepients: ${recepients[*]}" | |
cat - | gpg2 --encrypt --batch --use-agent --armor "${recepients[*]/#/--recipient=}" --output "$passphrase_file" | |
} | |
read_passphrase() { | |
passphrase_file="$1"; shift 1 | |
log "Reading passphrase from '$passphrase_file'" | |
gpg2 --decrypt --use-agent --batch --no-verbose --quiet "$passphrase_file" || log "Failed to decrypt the passphrase" error | |
} | |
#endregion | |
main() { | |
if [ -n "$ANSIBLE_VAULT_PASSPHRASE" ]; then | |
log 'Using variable ANSIBLE_VAULT_PASSPHRASE' | |
echo "$ANSIBLE_VAULT_PASSPHRASE" | |
exit 0 | |
fi | |
if [ ! -f "$ANSIBLE_VAULT_PASSPHRASE_FILE" ]; then | |
log "Generating new vault passphrase" | |
generate_passphrase | store_passphrase "$ANSIBLE_VAULT_PASSPHRASE_FILE" "${ANSIBLE_VAULT_PASSPHRASE_RECIPIENTS}" | |
fi | |
read_passphrase "$ANSIBLE_VAULT_PASSPHRASE_FILE" | |
} | |
main |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment