繁体   English   中英

在 Azure powershell 任务中添加/获取 Azure Keyvault 的秘密

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

I am trying to set the secrets inside my Azure Keyvault using the Azure Powershell Task in Azure DevOps. 我使用以下代码:

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

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

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

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

因此,我通过将服务主体和构建服务器都添加到具有 get、list、set secrets 权限的访问策略中来确保服务主体和构建服务器对 keyvault 具有正确的访问权限。

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

########################################################################################
$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
########################################################################################

通过在内联脚本的开头添加此代码并使用带有 commando 的配置文件作为 -DefaultProfile 的变量。

我还启用了使脚本能够访问 Oauth 令牌的选项。 在此处输入图像描述

是否有人也试图从 Azure DevOps 中的 powershell 任务中设置秘密。 或者知道为什么 powershell 脚本无法访问密钥库。 azurermContext 突击队为我提供了正确的 output,甚至尝试了 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)

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

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

即调用Add-AzureRmAccount -KeyVaultAccessToken

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

我用以下方法解决了我的问题。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM