提问人:Damo 提问时间:11/17/2023 更新时间:11/17/2023 访问量:38
使用 Powershell 将 Azure KeyVault 机密从一个保管库复制到另一个保管库,支持所有字符
Copy Azure KeyVault secrets from one Vault to Another using Powershell, supporting all characters
问:
我需要将存储在 Azure KeyVault 中的机密从一个保管库迁移到另一个保管库。
我有一个几乎可以工作的脚本;但是,某些密码中带有&,导致密码无法完整写入。它将密钥写入 &,但省略任何内容。
我试图逃避&,但这似乎不起作用。
我得到的错误是:
“19!7e”不被识别为内部或外部命令,可操作 程序或批处理文件。
这是 secret 的内容,在 &.
我需要修改什么?
Param(
[string] $originVault = 'a',
[string] $originSubscriptionId = 'b',
[string] $destinationVault = 'c',
[string] $destinationSubscriptionId = 'd',
[string] $disableDestinationSecrets = $true
)
# 1. Set the source subscription id.
Write-Host "Setting origin subscription to: $($originSubscriptionId)..."
az account set -s $originSubscriptionId
# 1.1 Get all secrets
Write-Host "Listing all origin secrets from vault: $($originVault)"
$originSecretKeys = az keyvault secret list --vault-name $originVault -o json --query "[].name" | ConvertFrom-Json
# 1.3 Loop secrets into PSCustomObjects
$secretObjects = $originSecretKeys | ForEach-Object {
Write-Host " - Getting secret value for '$($_)'"
$secret = az keyvault secret show --name $_ --vault-name $originVault -o json | ConvertFrom-Json
[PSCustomObject]@{
secretName = $_;
secretValue = $secret.value;
}#endcustomobject.
}#endforeach.
Write-Host "Done fetching secrets..."
# 2. Set the destination subscription id.
Write-Host "Setting destination subscription to: $($destinationSubscriptionId)..."
az account set -s $destinationSubscriptionId
# 2.2 Loop secrets objects, and set secrets in destination vault
Write-Host "Writing all destination secrets to vault: $($destinationVault)"
#doesn't work
# $secretObjects | ForEach-Object {
# Write-Host " - Setting secret value for '$($_.secretName)'"
# az keyvault secret set --vault-name $destinationVault --name "$($_.secretName)" --value "$($_.secretValue)" --disabled $disableDestinationSecrets -o none
# }
##also doesn't work
$secretObjects | ForEach-Object {
Write-Host " - Setting secret value for '$($_.secretName)'"
$escapedSecretValue = $_.secretValue -replace '&', '``&'
az keyvault secret set --vault-name $destinationVault --name "$($_.secretName)" --value "$escapedSecretValue" --disabled $disableDestinationSecrets -o none
}
# 3. Clean up
Write-Host "Cleaning up and exiting."
Remove-Variable secretObjects
Remove-Variable originSecretKeys
Write-Host "Finished."
原作者:https://zimmergren.net/backup-azure-key-vault-secrets-keys-certificates/
答:
0赞
agamil
11/17/2023
#1
请在命令中将密钥值括在单引号 (') 中,而不是 (“)。
所以,你的命令可能是这样的
az keyvault secret set --vault-name $destinationVault --name "$($_.secretName)" --value '$($_.secretValue)' --disabled $disableDestinationSecrets -o none
评论
0赞
Damo
11/17/2023
抱歉,使用单引号时,错误现在是 --disabled 此时是意外的。秘密根本没有写出来。
评论