How do I copy over all secrets from one Azure Keyvault to another using Powershell
this is just too triggering (no offense), here's a more "powershelly" version:
Param(
[Parameter(Mandatory)]
[string]$sourceVaultName,
[Parameter(Mandatory)]
[string]$destVaultName
)
Connect-AzAccount
$secretNames = (Get-AzKeyVaultSecret -VaultName $sourceVaultName).Name
$secretNames.foreach{
Set-AzKeyVaultSecret -VaultName $destVaultName -Name $_ `
-SecretValue (Get-AzKeyVaultSecret -VaultName $sourceVaultName -Name $_).SecretValue
}
Just to sum it up:
Parameters are mandatory with this change and you can tab complete them, so you dont have to remember which one is first.
Using foreach
is a bit cleaner than using do\while
(certainly less cognitive effort).
You dont have to cast values to text and encrypt it back, you can just use encrypted value to assign it to new secret
There is now!
import-module AzureRM.keyvault
$sourceVaultName = $args[0]
$destVaultName = $args[1]
Connect-AzureRmAccount
#unfortunately you can only access secret values one at a time, by name. so this gets the names first
$names = (Get-AzureKeyVaultSecret -VaultName $sourceVaultName | select Name)
$i=0
do {
$rawSecret = (Get-AzureKeyVaultSecret -VaultName $sourceVaultName -Name $names[$i].Name).SecretValueText
$AKVsecret = ConvertTo-SecureString $rawSecret -AsPlainText -Force
Set-AzureKeyVaultSecret -VaultName $destVaultName -Name $names[$i].Name -SecretValue $AKVsecret
$i++
} while($i -lt $names.length)
You can call it using
script.ps1 source-keyvault-name dest-keyvault-name
The script can be translated to the new coolness of az.cli
Param(
[Parameter(Mandatory)]
[string]$sourceVaultName,
[Parameter(Mandatory=$false)]
[string]$sourceSubscription,
[Parameter(Mandatory)]
[string]$destVaultName,
[Parameter(Mandatory=$false)]
[string]$descriptionSubscription
)
# az login
if($sourceSubscription){
az account set --subscription $sourceSubscription
}
Write-Host 'Reading secrets ids from' $sourceVaultName
$secretNames = az keyvault secret list --vault-name $sourceVaultName -o json --query "[].name" | ConvertFrom-Json
Write-Host 'Reading secrets values'
$secrets = $secretNames | % {
$secret = az keyvault secret show --name $_ --vault-name $sourceVaultName -o json | ConvertFrom-Json
[PSCustomObject]@{
name = $_;
value = $secret.value;
}
}
Write-Host 'writing secrets'
if($descriptionSubscription){
az account set --subscription $descriptionSubscription
}
$secrets.foreach{
az keyvault secret set --vault-name $destVaultName --name $_.name --value $_.value
}