This blog demonstrates how we can easily copy all Azure KeyVault secrets to another KeyVault using Powershell script and bash/Azure CLI script. Sometimes your application keyvalut may contain significant numbers for secrets and you are planning to deploy your code to a new environment where all secrets need to move from the existing keyvault. At this point, you have created a new keyvault but don’t have any secrets there.
Below are the best and easiest ways to copy all selected material from one keyvault to another,
- Copy Azure KeyVault using Powershell script
- Copy Azure KeyVault using Azure CLI
We can follow either here…..Let’s discuss.
Here, we are copying 4 secrets from the source keyvault called myKeyVault2020 for the demonstrations.
Option 1: Copy Azure KeyVault using Powershell script
Now we want to copy secrets that are not already present in the destination keyvault called kv-myapps-2021 using Azure Powershell.
Param(
[Parameter(Mandatory)]
[string]$sourceKvName,
[Parameter(Mandatory)]
[string]$destKvName
)
Connect-AzAccount
$secretNames = (Get-AzKeyVaultSecret -VaultName $sourceKvName).Name
$secretNames.foreach{
Set-AzKeyVaultSecret -VaultName $destKvName -Name $_ `
-SecretValue (Get-AzKeyVaultSecret -VaultName $sourceKvName -Name $_).SecretValue
}
We can see that all secrets have been copied successfully to kv-myapps-2021.
Option 2: Copy Azure KeyVault using Azure CLI
We can also copy all secrets using the below Bash script to a new destination keyvault called kv-myapps-2023.
Source_Kv_Name="myKeyVault2020"
Dest_Kv_Name="kv-myapps-2023"
SECRETS+=($(az keyvault secret list --vault-name $Source_Kv_Name --query "[].id" -o tsv))
for SECRET in "${SECRETS[@]}"; do
SECRETNAME=$(echo "$SECRET" | sed 's|.*/||')
SECRET_CHECK=$(az keyvault secret list --vault-name $Dest_Kv_Name --query "[?name=='$SECRETNAME']" -o tsv)
if [ -n "$SECRET_CHECK" ]
then
echo "$SECRETNAME already exists in $Dest_Kv_Name"
else
echo "Copying $SECRETNAME from Source KeyVault: $Source_Kv_Name to Destination KeyVault: $Dest_Kv_Name"
SECRET=$(az keyvault secret show --vault-name $Source_Kv_Name -n $SECRETNAME --query "value" -o tsv)
az keyvault secret set --vault-name $Dest_Kv_Name -n $SECRETNAME --value "$SECRET" >/dev/null
fi
done
Let’s check the destination key vault. Awesome! All secrets are copied.
I hope you find this information useful.
Happy Reading!