Copy Key Vault Secrets

By Jani Nevalainen

A practical approach to copying secrets between Azure Key Vaults.
In our latest series of tech tips, we tackle one of the most sought after questions. Sometimes you might notice that you would need to copy your secrets in an Azure 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. Now you have a perfect copy of your Key Vault secrets.
# 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."
Related insights

Custom Metrics with Application Insights
How to leverage custom metrics in Application Insights for better observability.


Bicep Local Extensions
Exploring the new local extensions feature in Azure Bicep for infrastructure as code.


Azure Change Analysis
Using Azure Change Analysis to track infrastructure changes.
