Add/get 在 Azure devops 中使用 Azure powershell 任务对 Azure Keyvault 保密

Add/get secret to Azure Keyvault with Azure powershell task in Azure devops

我正在尝试使用 Azure DevOps 中的 Azure Powershell 任务在我的 Azure Keyvault 中设置机密。 我使用以下代码:

Set-AzureKeyVaultSecret -VaultName $KeyvaultName -Name $SecretName -SecretValue $secretvalue

所有名称和值都设置在变量中,并尝试在没有变量的情况下使用它。 该值使用以下代码保存为安全字符串。ConvertTo-SecureString

但是当我 运行 我的 Azure DevOps 发布管道中的这个 powershell 代码时,我不断收到以下错误消息:

Cannot retrieve access token for resource 'AzureKeyVaultServiceEndpointResourceId'.  Please ensure that you have provided the appropriate access tokens when using access token login.

因此,我通过将服务主体和构建服务器都添加到具有获取、列表、设置机密权限的访问策略,确保了服务主体和构建服务器对密钥库具有正确的访问权限。

我还添加了以下代码行以确保正确加载配置文件

########################################################################################
$azureRmProfile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile
$profileClient = New-Object -TypeName Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient -ArgumentList ($azureRmProfile)
$context = Get-AzureRmContext
$AzureToken = $profileClient.AcquireAccessToken($context.Tenant.Id)
Add-AzureRmAccount -AccessToken $AzureToken.AccessToken -AccountId $AzureToken.UserId
########################################################################################

通过在内联脚本的开头添加此代码,并将带有突击队的配置文件用作 -DefaultProfile 的变量。

我还启用了使脚本能够访问 Oauth 令牌的选项。

有没有人也试过在 Azure DevOps 的 powershell 任务中设置 secret。或者知道为什么 powershell 脚本无法访问 keyvault。 azurermContext commando 为我提供了正确的输出,甚至尝试了 Get-AzureRmKeyvault 命令来确定与环境的连接是否已经正确设置。而且这也没有带来任何问题。

以下肯定有效(经常使用)

Set-AzContext -SubscriptionId $SubscriptionId
## $SubscriptionId is a subscription ID where is the target KV

$Secretvalue = ConvertTo-SecureString $SecretValuePlainText -AsPlainText -Force
## $SecretValuePlainText is the secret to store

Set-AzKeyVaultSecret -VaultName $KeyVaultName -Name $SecretName -SecretValue $Secretvalue -ErrorVariable setSecretError -Expires $ExpirationDate -NotBefore $ActivationDate
## $SecretName, $ExpirationDate, $ActivationDate - obvious :)

当然,如果您不是从脚本或内联中引用变量,而是从发布中引用变量,请使用 $(variable_name)

服务Principal/Service我们为此使用的连接是临时的目标订阅所有者(或密钥保管库,由您决定)。

我遇到了完全相同的问题。 发现问题是缺少访问令牌。

-KeyVaultAccessToken 当你调用 Add-AzureRmAccount.

在此处找到解决方案:https://github.com/Azure/azure-powershell/issues/4818#issuecomment-376155173

我用以下内容解决了我的问题。

我使用了基于托管身份的服务连接。这需要一些解决方法来访问像 @john 提到的密钥库。但这是不必要的。通过基于服务主体创建新的服务连接。此解决方法不是必需的,并且解决了问题。