Created
February 14, 2024 07:23
-
-
Save ebongzzang/13c7c5dd5093a12c2b05d2ac31866b39 to your computer and use it in GitHub Desktop.
Copy all vault secrets under secret backend A into B recursively
This file contains 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 -e | |
SOURCE_KV=$1 | |
TARGET_KV=$2 | |
results=() | |
list_secrets() { | |
local path=$1 | |
# List secrets at the current path | |
secrets=$(vault kv list -format=json "${SOURCE_KV}/${path}" 2>/dev/null) | |
if [ "$?" -ne 0 ]; then | |
echo "Error listing secrets at path: ${SOURCE_KV}/${path}" | |
return | |
fi | |
# If there are secrets, process them | |
if [ ! -z "$secrets" ] && [ "$secrets" != "null" ]; then | |
for secret in $(echo "${secrets}" | jq -r '.[]'); do | |
# If the secret is a path (ends with /), list secrets recursively | |
if [[ "$secret" == */ ]]; then | |
list_secrets "${path}${secret}" | |
else | |
# Print the secret path | |
results+=("${path}${secret}") | |
fi | |
done | |
fi | |
} | |
# Start listing secrets from the root of the secret engine | |
list_secrets "" | |
for result_path in "${results[@]}"; do | |
# Read the secret | |
secret_data=$(vault kv get -format=json -field=data "${SOURCE_KV}/${result_path}") | |
if [ "$?" -ne 0 ]; then | |
echo "Error reading secret: ${result_path}" | |
continue | |
fi | |
echo "Copy ${SOURCE_KV}/${result_path} into ${TARGET_KV}/${result_path}" | |
echo "${secret_data}" | vault kv put "${TARGET_KV}/${result_path}" - | |
done | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment