Sometimes you might notice that you would need to copy your secrets in a key vault to another, when for example you have created a set of environmental variables in your sandbox, and want to move them to testing. When you have tens or even hundreds of them, it’s a jarring task copying them by hand.
Lazy to the rescue! Using this script, by replacing the source and destination vault names and subscriptions, you can copy every secret from one key vault to another. Vault parameter needs just the name, not the URL, and subscription is the ID of Azure subscription.
# Set your Azure Key Vault details and subscriptions
$sourceKV = 'XXX'
$sourceSub = 'XXX'
$destKV = 'XXX'
$destSub = 'XXX'
# Log in to Azure and set the context to the source subscription
az account set --subscription $sourceSub
# Retrieve the list of secret names from the source KV
$secretNames = az keyvault secret list --vault-name $sourceKV --query "[].name" -o json | ConvertFrom-Json
# Switch the context to the destination subscription
az account set --subscription $destSub
# Loop through secrets, get values from the source KV, and set it in the destination KV
foreach ($name in $secretNames) {
$value = az keyvault secret show --name $name --vault-name $sourceKV --query "value" -o tsv
az keyvault secret set --vault-name $destKV --name $name --value $value
Write-Host "Copied secret $name to $destKV"
# Clear the secret value to minimize sensitive data exposure
$value = $null
}
# Clear the secret names to minimize sensitive data exposure
$secretNames = $null
Write-Host "All secrets copied successfully."
Author:Jani Nevalainen
More stories about Azure