Synchronize Azure Key Vault Secrets using Azure PowerShell
Problem Statement
There is no built-in way in Azure Portal to copy secrets between two Key Vaults located in different subscriptions. The usage of Get-AzKeyVaultSecret is not trivial either as the values are not fetched when selecting multiple secrets.
Recently, we had to get multiple secrets selected by a filter string and copy them into different key vaults to separate some development and production data which has let to the solution presented below.
Solution
Source Code
The source code is available from github.
It runs both in Cloud Shell and locally, but you need to login to Azure first when running it locally and download the Az modules.
Parameters and Execution
- Download the script
- Connect to Azure (when running locally)
- Run the script:
. ./Sync-KeyVaultSecret.ps1 -SourceVaultName {Source Key Vault Name} -SourceSubscriptionId {Source Key Vault SubscriptionId} -FilterString {Filtering String} -DestinationSubscriptionId {Destination Key Vault SubscriptionId} -DestinationVaultName {Destination Key Vault Name}
Annotations
- When fetching the secrets, the cmdlet "Get-AzKeyVaultSecret" needs to be called multiple times as values are only fetched when parameterized with a single secret
- The Subscription Context needs to be changed before importing the fetched secrets
- The accounts used to authenticate Azure needs Read permissions on the source key vault and Contributor access on the destination key vault.