簡體   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