Monday, September 6, 2021

Backup objects into another vault in another subscription

 How to: Backup objects into another vault in another subscription

In this section, I'm getting the secret values and saving them into another vault directly. We want to do this without touching any disk files.

With this approach, we're simply fetching all secrets from Vault1 in Subscription1, and saving them to Vault2 in Subscription2. However, remember that the secrets we fetch now are not encrypted to your subscription, hence it's not a good idea to persist them in memory, sessions or disk. Here I'm not saving it to any variables.

Make sure you have installed Azure CLI for windows in order to run the below script.


    [parameter(mandatory)] [string] $sourceVaultName,

    [parameter(mandatory)] [string] $sourceSubscriptionId,

    [parameter(mandatory)] [string] $destinationVaultName,

    [parameter(mandatory)] [string] $destinationSubscriptionId,

    [string] $destinationSecretsDisable = $true


# 1. Set the source subscription id. 

Write-Host "Setting origin subscription to: $($sourceSubscriptionId)..."

az account set -s $sourceSubscriptionId

# 1.1 Get all secrets

Write-Host "Listing all origin secrets from vault: $($sourceVaultName)"

$originSecretKeys = az keyvault secret list --vault-name $sourceVaultName  -o json --query "[].name"  | ConvertFrom-Json

# 1.3 Loop the secrets, and push the value to the destination vault without instantiating new variables.

$originSecretKeys | ForEach-Object {

    $secretName = $_

    Write-Host " - Getting '$($secretName)' from origin, and setting in destination..."

    az keyvault secret set --name $secretName --vault-name $destinationVaultName -o none --value(az keyvault secret show --name $secretName --vault-name $sourceVaultName -o json --query "value")


Write-Host "Secrets restored."

You can call the above script as mentioned below

.\CopySecretsToAnotherVault.ps1 -originVault "vault1-name" -originSubscriptionId "SUBSCRIPTION GUID" -destinationVault "vault2-name" -destinationSubscriptionId "SUBSCRIPTION GUID"

No comments:

Post a Comment