如何在 Powershell Azure 函数中使用 Get-AzKeyVaultSecret 2.x

How to use Get-AzKeyVaultSecret in Powershell Azure Function 2.x

我正在设置需要 Azure KeyVault 中的密钥的 Powershell Azure Function。可以使用@Microsoft.KeyVault(SecretUri='MySecretUriWithVersion') 方法检索大多数密钥。

其中一个键经常变化。因此不能使用SecretUri。

所有密钥都存储在同一个 KeyVault 中,并且函数有一个可以读取、列出和更改所有密钥的 MSI。

我正在使用需要更新的刷新令牌。每次我的代码运行时都会更新这个值,需要在 keyvault

中更新
Connect-AzAccount -Identity

#Works
Get-AzKeyVault -VaultName $VaultName -ResourceGroupName $rgName

#Not working
Get-AzKeyVaultSecret -VaultName $VaultName -Name $KeyName

预期输出:代码检索密钥。

Actual output: ERROR: Operation returned an invalid status code 'Unauthorized' Microsoft.Azure.WebJobs.Script.Rpc.RpcException : Result: ERROR: Operation returned an invalid status code 'Unauthorized' Exception: Operation returned an invalid status code 'Unauthorized' Stack: at Microsoft.Azure.KeyVault.KeyVaultClient.GetSecretWithHttpMessagesAsync(String vaultBaseUrl, String secretName, String secretVersion, Dictionary`2 customHeaders, CancellationToken cancellationToken) dlet.ProcessRecord()

取自微软:https://docs.microsoft.com/en-us/azure/key-vault/quick-create-powershell

您是否尝试过使用点符号来检索这些密钥?

(Get-AzKeyVaultSecret -vaultName $VaultName -name $KeyName).SecretValueText

如果这不起作用,您可以查看有关 ManagedAppServices 的 github 问题:https://github.com/Azure/azure-powershell/issues/8983

似乎与您遇到的问题相同。

此外,如果您因 secretValueText 被弃用而遇到任何问题,请参阅此 link

现在有一个新的方法。

$secret = Get-AzKeyVaultSecret -VaultName "<your-unique-keyvault-name>" -Name "ExamplePassword"
$ssPtr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secret.SecretValue)
try {
  $secretValueText = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($ssPtr)
} finally {
  [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ssPtr)
}
Write-Output $secretValueText

参考:https://docs.microsoft.com/en-us/azure/key-vault/secrets/quick-create-powershell

原始错误现已在 Azure Functions 中修复。

仍然需要检索密钥保管库中经常更新的密钥。为此,我使用这个:

(Get-AzKeyVaultSecret MyVaultName -Name MySecretName).secretvalue | ConvertFrom-SecureString -AsPlainText