Recently I had to copy more than 50 secrets (names and values) from one Azure KeyVault to another one. The two KeyVaults are on different subscriptions. Doing this manually is very tiresome and error prone. So I decided to do it in the right way…
Here is my favorite reference for Azure Powershell modules and commands.
So back to the work, first of all I imported the Az.KeyVault module:
Import-Module Az.KeyVault
Then I needed to login and connect to the Azure subscription containing the source KeyVault:
Connect-AzAccount -SubscriptionId 'ssssssss-ssss-ssss-ssss-ssssssssssss'
Having done that, I proceeded with running the Get-AzKeyVaultSecret module and saving the secret names in a list:
$sourceVaultName = "skv"
$targetVaultName ="tkv"
$secretNames = (Get-AzKeyVaultSecret -VaultName $sourceVaultName).Name
Now I could loop through these names, use Get-AzKeyVaultSecret again, and get the secret values. Note that the “disabled” secrets have null value. So I did a simple “null-check” before saving the name-value pairs in the final list:
$secretValuePairs = @()
foreach ($secret in $secretNames)
{
$obj = [PSCustomObject]@{
Name = $secret
Value = (Get-AzKeyVaultSecret -VaultName $sourceVaultName -Name $secret).SecretValue
}
if ($obj.Value -ne $null) {
$secretValuePairs += $obj
Write-Host "$($obj.Name) : $($obj.Value)"
}
}
Now all I had to do was, to change the subscription and import the secret key-value pairs to the destination KeyVault:
Connect-AzAccount -SubscriptionId 'tttttttt-tttt-tttt-tttt-tttttttttttt'
$secretValuePairs.foreach{
Set-AzKeyVaultSecret -VaultName $targetVaultName -Name $_.Name -SecretValue $_.Value
}
This way I managed to transfer the secrets fast and mistake-free. I hope this saves someone’s time in future.