Back Back
to to
Stories Stories

Feb 23rd 2024

Copy your secrets from key vault to another

hero-image

Sometimes you might notice that you would need to copy your secrets in a key vault to another, when for example you have created a set of environmental variables in your sandbox, and want to move them to testing. When you have tens or even hundreds of them, it’s a jarring task copying them by hand.

Lazy to the rescue! Using this script, by replacing the source and destination vault names and subscriptions, you can copy every secret from one key vault to another. Vault parameter needs just the name, not the URL, and subscription is the ID of Azure subscription.

# Set your Azure Key Vault details and subscriptions
$sourceKV = 'XXX'
$sourceSub = 'XXX'
$destKV = 'XXX'
$destSub = 'XXX'

# Log in to Azure and set the context to the source subscription
az account set --subscription $sourceSub

# Retrieve the list of secret names from the source KV
$secretNames = az keyvault secret list --vault-name $sourceKV --query "[].name" -o json | ConvertFrom-Json

# Switch the context to the destination subscription
az account set --subscription $destSub

# Loop through secrets, get values from the source KV, and set it in the destination KV
foreach ($name in $secretNames) {
    $value = az keyvault secret show --name $name --vault-name $sourceKV --query "value" -o tsv
    az keyvault secret set --vault-name $destKV --name $name --value $value
    Write-Host "Copied secret $name to $destKV"
    
    # Clear the secret value to minimize sensitive data exposure
    $value = $null
}
# Clear the secret names to minimize sensitive data exposure
$secretNames = $null

Write-Host "All secrets copied successfully."

Author:Jani Nevalainen

Came this far? Why not say Hi!

Teemu Tapanila

Teemu Tapanila

CTO, Principal Architect

teemu.tapanila@mallow.fi

+358 452 135 655

Riku Pilli

Riku Pilli

Sales Manager

riku.pilli@mallow.fi

+358 40 725 0888