无法在 Azure Devops 上的 powershell 脚本 运行 中访问 Azure 密钥保管库机密

Unable to access Azure Key vault secret in a powershell script running on Azure Devops

我有一个 powershell 脚本,它尝试使用此命令检索存储在 Azure 密钥保管库中的机密。

$password = (Get-AzureKeyVaultSecret -vaultName $vaultName -name $secretName).SecretValueText

当我在本地执行 powershell 脚本时,它工作得很好。但是,当我尝试在 Azure Devops 上做同样的事情时,它没有给出以下错误。

[error]Operation returned an invalid status code 'Forbidden'

我觉得这不是访问策略问题,因为我能够在本地使用 powershell 脚本 运行 在我的保管库上成功执行 read/write。

我很确定这是一个访问策略问题。

转到您的 DevOps 项目设置 - 管道 - 服务连接并单击 "Update Service Connection"(使用对话框的完整版本)。在那里您可以找到订阅 ID 和服务主体 ID。

然后您必须为此 SPN 授予显式权限:

Login-AzureRmAccount -subscription <YourSubscriptionID>
$spn= Get-AzureRmADServicePrincipal -spn <YourSPN>
Set-AzureRmKeyVaultAccessPolicy -VaultName <YourVaultName> -ObjectId $spn.Id -PermissionsToSecrets get,list;