Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I copy over all secrets from one Azure Keyvault to another using Powershell

Tags:

We recently found ourselves needing to copy over every single secret (name and value) from one Azure KeyVault to a newly created one. I found ways to restore the secrets from a backup, but we didn't have a backup. Is there a Powershell script that can just loop through every name/value combo in a source vault and copy it to a destination vault?

like image 446
Tom Warner Avatar asked Apr 10 '19 17:04

Tom Warner


People also ask

How do you copy secrets from one Keyvault to another?

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.

How do you pull secrets from Azure key vault?

If you click on the current version, you can see the value you specified in the previous step. By clicking "Show Secret Value" button in the right pane, you can see the hidden value. You can also use Azure CLI, or Azure PowerShell to retrieve previously created secret.

How do you get all the secrets in one call key Azure vault?

If you are using the newer Azure. Security. KeyVault. Secrets package then you can get all the secrets by using the GetPropertiesOfSecretsAsync method, then iterating over each result calling GetSecretAsync .


1 Answers

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

like image 173
4c74356b41 Avatar answered Oct 17 '22 06:10

4c74356b41