Last active
September 28, 2021 02:19
-
-
Save pbatey/48f3dbf0d9f0695f09920f7291a6ec3d to your computer and use it in GitHub Desktop.
Copy values from one Hashicorp Vault path to another (works with Vault v1.1.2)
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 | |
tmp=$(mktemp -d) | |
trap "{ rm -rf $tmp; }" EXIT | |
# ensure we were given two command line arguments | |
if [[ $# -ne 2 ]]; then | |
echo 'usage: vault-cp SOURCE DEST' >&2 | |
exit 1 | |
fi | |
source=$1 | |
dest=$2 | |
# check source | |
if vault read "$source" >/dev/null; then | |
true | |
else | |
exit $? | |
fi | |
# check destination | |
if dest_check=$(vault read "$dest" 2>&1); then | |
if [[ $dest_check != "No value found at $dest" ]]; then | |
# only overwrite if user explicitly confirms | |
overwrite='n' | |
printf 'Destination "%s" already exists...overwrite? [y/N] ' "$dest" | |
read -r overwrite | |
if [[ ! $overwrite =~ ^[Yy]$ ]]; then | |
echo 'vault-cp: copying has been aborted' >&2 | |
exit 1 | |
fi | |
fi | |
else | |
exit $? | |
fi | |
# create a file for each value | |
cmd="vault write $dest" | |
for key in $(vault read -format=yaml "$source" | awk '/^ [^ ]*:/ {gsub(":","");print $1}'); do | |
echo $key | |
file=$tmp/$key | |
cmd="$cmd $key=@$file" | |
vault read -field=$key $source > $file | |
done | |
$cmd |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inspired by https://gist.github.com/elasticdog/e82f0b8e63407cbb6af69341cb9d0336, but it didn't work with the version of Vault I was using.