Mallow
Azure Tips · 23. helmikuuta 2024

Kopioi Key Vault -salaisuudet Key Vaultista toiseen

Jani Nevalainen

Kirjoittaja: Jani Nevalainen

Kopioi Key Vault -salaisuudet Key Vaultista toiseen

Käytännön lähestymistapa salaisuuksien kopioimiseen Azure Key Vaultien välillä.

Joskus tulee vastaan tarve kopioida salaisuudet yhdestä Azure Key Vaultista toiseen. Tyypillinen tilanne on, että olet koonnut ympäristömuuttujat sandbox-ympäristöön ja haluat siirtää ne testaukseen. Kun salaisuuksia on kymmeniä tai satoja, käsin kopiointi ei ole järkevää.

Tässä auttaa yksinkertainen skripti. Kun vaihdat source- ja target-Key Vaultin nimet sekä Azure-tilaukset (subscription), voit kopioida kaikki salaisuudet kerralla. --vault-name-parametri käyttää Key Vaultin nimeä, ei URL-osoitetta.

Huomio: tämä skripti kopioi salaisuuden arvon ja luo sen kohde-Key Vaultiin. Kaikki metatiedot eivät välttämättä siirry sellaisenaan.

# 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."