1
0

pkgs/clerie-sops: Add actions to clerie-sops-edit

This commit is contained in:
clerie 2024-05-12 14:34:00 +02:00
parent e2b53c9c50
commit d22a3d447b

View File

@ -5,8 +5,42 @@
set -euo pipefail set -euo pipefail
print_help() {
cat << EOF
clerie-sops-edit <secrets_file> <action> <key>
This script allows editing single secrets in a secrets file by key.
<secrets_file> is a sops secrets file
<action> is one of "edit", "read", "set" and "append"
<key> is the key of the secret in the secrets file to modify
EOF
}
if [[ $# != 3 ]]; then
print_help
exit 1
fi
SECRETS_FILE="$1" SECRETS_FILE="$1"
KEY="$2"
if [[ ! -f "${SECRETS_FILE}" ]]; then
echo "File \"${SECRETS_FILE}\" does not exist"
echo
print_help
exit 1
fi
ACTION="$2"
if ! echo "edit read set append" | grep -wq "${ACTION}"; then
echo "Action \"${ACTION}\" not supported"
echo
print_help
exit 1
fi
KEY="$3"
KEY_SELECTOR="$(jq -Rsc '[.]' <(echo -n "${KEY}"))" KEY_SELECTOR="$(jq -Rsc '[.]' <(echo -n "${KEY}"))"
if [[ -n $EDITOR ]]; then if [[ -n $EDITOR ]]; then
@ -14,12 +48,36 @@ if [[ -n $EDITOR ]]; then
fi fi
TMP_FILE="$(mktemp)" TMP_FILE="$(mktemp)"
DECRYPT_ERROR_FILE="$(mktemp)"
clerie-sops --decrypt --extract "${KEY_SELECTOR}" "${SECRETS_FILE}" > "${TMP_FILE}" if ! clerie-sops --decrypt --extract "${KEY_SELECTOR}" "${SECRETS_FILE}" > "${TMP_FILE}" 2> "${DECRYPT_ERROR_FILE}"; then
# Ignore that the key does not exist, but fail for all other errors
if ! cat "${DECRYPT_ERROR_FILE}" | grep -q "component .* not found"; then
cat "${DECRYPT_ERROR_FILE}"
exit 1
fi
fi
TMP_FILE_HASH_BEFORE="$(sha256sum "${TMP_FILE}")" TMP_FILE_HASH_BEFORE="$(sha256sum "${TMP_FILE}")"
vim "${TMP_FILE}" case "${ACTION}" in
edit)
"${EDITOR}" "${TMP_FILE}"
;;
read)
cat "${TMP_FILE}"
;;
set)
cat > "${TMP_FILE}"
;;
append)
cat >> "${TMP_FILE}"
;;
*)
echo "Unsupported action"
exit 1
;;
esac
TMP_FILE_HASH_AFTER="$(sha256sum "${TMP_FILE}")" TMP_FILE_HASH_AFTER="$(sha256sum "${TMP_FILE}")"