Copy Azure KeyVault secrets to another KeyVault using Azure CLI

I am going to show how you can copy Azure KeyVault secrets to another KeyVault using Azure CLI.

I have two key vaults,

keyvaultold – Contains secrets1 to secret7

keyvaultnewtest – Contains secret7

I want to copy secrets that are not already present in keyvaultnewtest from keyvaultold

I created a bash script using Azure CLI, I was able to achieve this!

#!/bin/bash

SOURCE_KEYVAULT="keyvaultold"
DESTINATION_KEYVAULT="keyvaultnewtest"

SECRETS+=($(az keyvault secret list --vault-name $SOURCE_KEYVAULT --query "[].id" -o tsv))

for SECRET in "${SECRETS[@]}"; do

SECRETNAME=$(echo "$SECRET" | sed 's|.*/||')

SECRET_CHECK=$(az keyvault secret list --vault-name $DESTINATION_KEYVAULT --query "[?name=='$SECRETNAME']" -o tsv)


if [ -n "$SECRET_CHECK" ]
then
    echo "A secret with name $SECRETNAME already exists in $DESTINATION_KEYVAULT"
else
    echo "Copying $SECRETNAME to KeyVault: $DESTINATION_KEYVAULT"
    SECRET=$(az keyvault secret show --vault-name $SOURCE_KEYVAULT -n $SECRETNAME --query "value" -o tsv)
    az keyvault secret set --vault-name $DESTINATION_KEYVAULT -n $SECRETNAME --value "$SECRET" >/dev/null
fi

done

Output sample from running the script

Awesome! Checking keyvaultnewtest I can see the secrets that were not present are now copied successfully from keyvaultold

Hopefully this bash/Azure CLI script will assist you – thanks for reading!

GitHub Repository

GitHub Gist

2 comments

  1. Thanks for the script!

    Small typo on line 12 though:
    SECRET_CHECK=$(az keyvault secret list –vault-name keyvaultnewtest –query “[?name==’$SECRETNAME’]” -o tsv)

    Should be:

    SECRET_CHECK=$(az keyvault secret list –vault-name $DESTINATION_KEYVAULT –query “[?name==’$SECRETNAME’]” -o tsv)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s