sops-decrypt/entrypoint.sh

67 lines
2.6 KiB
Bash

#!/bin/sh
set -e
# --- Configuration (from Environment Variables) ---
APP_NAME="${APP_NAME:-sops-init}"
GPG_KEY_PATH="${GPG_KEY_PATH:-/run/secrets/gpg_key}"
GPG_PASSPHRASE_PATH="${GPG_PASSPHRASE_PATH}"
SOPS_INPUT_DIR="${SOPS_INPUT_DIR:-/config_in}"
SOPS_OUTPUT_DIR="${SOPS_OUTPUT_DIR:-/config_out}"
# --- Script Logic ---
echo "$APP_NAME: Configuration materializer started."
echo "➡️ $APP_NAME: Input Dir: '$SOPS_INPUT_DIR', Output Dir: '$SOPS_OUTPUT_DIR'"
# --- GPG Key Import and Unlocking ---
# (This section is unchanged as it is working correctly)
echo "🔄 $APP_NAME: Starting GPG Agent..."
unset GPG_AGENT_INFO
eval $(gpg-agent --daemon --pinentry-mode loopback)
if [ ! -f "$GPG_KEY_PATH" ]; then
echo "$APP_NAME: ERROR: GPG secret key not found at '$GPG_KEY_PATH'"
exit 1
fi
echo "🔐 $APP_NAME: Importing GPG private key..."
gpg --batch --import "$GPG_KEY_PATH"
if [ -n "$GPG_PASSPHRASE_PATH" ]; then
if [ ! -f "$GPG_PASSPHRASE_PATH" ]; then
echo "$APP_NAME: ERROR: GPG passphrase file not found at '$GPG_PASSPHRASE_PATH'"
exit 1
fi
echo "🔑 $APP_NAME: Unlocking key to cache passphrase with GPG Agent..."
KEY_FINGERPRINT=$(gpg --with-colons --import-options import-show --import < "$GPG_KEY_PATH" | awk -F: '/^sec:/ { print $5 }')
if [ -z "$KEY_FINGERPRINT" ]; then
echo "$APP_NAME: Could not determine GPG key fingerprint from key file."
exit 1
fi
echo " - Unlocking key with fingerprint: $KEY_FINGERPRINT"
echo "test" | gpg --quiet --batch --pinentry-mode loopback --passphrase-file "$GPG_PASSPHRASE_PATH" --sign -u "$KEY_FINGERPRINT" > /dev/null
echo " - Key unlocked and passphrase cached successfully."
fi
# --- File Processing Loop ---
echo "🔎 $APP_NAME: Processing all files in '$SOPS_INPUT_DIR'..."
# Find ALL files (-type f) in the input directory
find "$SOPS_INPUT_DIR" -type f | while read -r source_file; do
relative_path="${source_file#$SOPS_INPUT_DIR/}"
destination_file="${SOPS_OUTPUT_DIR}/${relative_path}"
# Ensure the destination directory exists
mkdir -p "$(dirname "$destination_file")"
# Attempt to decrypt the file. Redirect stderr to /dev/null to keep logs clean.
if sops --decrypt "$source_file" > "$destination_file" 2>/dev/null; then
# If decryption succeeds, log it.
echo " decrypted ✅ $relative_path"
else
# If decryption fails, it's not a SOPS file. Copy it verbatim instead.
echo " copied ↪️ $relative_path"
cp "$source_file" "$destination_file"
fi
done
echo "🎉 $APP_NAME: All files processed. Exiting."