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

azure devops service connection key vault
azure key vault
azure key vault powershell
azure devops task group variables
azure devops variable groups
use key vault in azure pipeline
azure devops powershell variables
azure key vault key vs secret

I am trying to set the secrets inside my Azure Keyvault using the Azure Powershell Task in Azure DevOps. I use the following code:

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

With the names and the value all setup inside variables and tried to use this without also variables. The value is saved as a secure string with the following code.ConvertTo-SecureString

But when I run this powershell code inside my Azure DevOps Release pipeline I keep getting following Error message:

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

So I've made sure that the service principal and the build server are having the right access on the keyvault by adding them both to the access policies with the get,list,set secrets permission.

I've also added following lines of code to make sure that the profile is loaded correctly

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

By adding this code in the beginning of the inline script and using the profile with the commando as variable to the -DefaultProfile.

I also enabled the option to enable the script to access the Oauth token.

Is there someone who also tried to set the secret from the powershell task in Azure DevOps. Or know why the powershell script can't get access on the keyvault. The azurermContext commando provided me with the right output, even tried the Get-AzureRmKeyvault command to figure out if the connection to the environment was already setup right. And that also didn't gave any problems.

below working for sure (using this reguarly)

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 :)

of course if your refer to variable not from script or inline, but from release the use $(variable_name)

Service Principal/Service Connection we use for this is temporary an Owner of target subscription (or key vault, up to you).

Azure Key Vault task, Azure Key Vault task for use in the jobs of all of your build and release By using the PowerShell cmdlet Set-AzureKeyVaultSecret. To add a secret to a key vault​, for example a secret named In the Add access policy blade, choose Secret permissions and ensure that Get and List are checked (ticked). I am trying to set the secrets inside my Azure Keyvault using the Azure Powershell Task in Azure DevOps. I use the following code: Set-AzureKeyVaultSecret -VaultName $KeyvaultName -Name $SecretName -SecretValue $secretvalue With the names and the value all setup inside variables and tried to use this without also variables.

I had the exact same issue. Found that the problem was a missing access token.

Namely -KeyVaultAccessToken when you call Add-AzureRmAccount.

Found the solution here: https://github.com/Azure/azure-powershell/issues/4818#issuecomment-376155173

Using secrets from Azure Key Vault in a pipeline, Azure DevOps Project – My Pipeline that will run a PowerShell Task and the script will then grant Get & List Secret permissions to the key vault use an Existing Key Vault, followed by adding 3 secrets for a service principal. Adding a secret to Key Vault. To add a secret to the vault, you just need to take a couple of steps. In this case, you add a password that could be used by an application. The password is called ExamplePassword and stores the value of hVFkk965BuUv in it. First convert the value of hVFkk965BuUv to a secure string by typing:

I fixed my question with the following.

I used a service connection that was based on a managed identity. And this needed some workaround to access the key vault like @john mentioned. But this was unnecessary. by creating a new service connection based on a service principal. This workaround was not necessary and fixed the issue.

Using Azure Key Vault Secrets with PowerShell Tasks in Azure , With Azure DevOps, you can get sensitive data like Connection Strings, Secrets, Azure DevOps accessing an Azure Key Vault using an Azure AD app Use this task in a build or release pipeline to download secrets such as In the following example, I'm adding a simple PowerShell task that outputs  If the secret already exists, this cmdlet creates a new version of that secret. By using the Azure CLI. To add a secret to a key vault, for example a secret named SQLPassword with the value Pa$$w0rd, type: Azure CLI. az keyvault secret set --vault-name 'ContosoKeyVault' --name 'SQLPassword' --value 'Pa$$w0rd'.

Using Azure Key Vault Secrets from your Azure DevOps pipelines, below working for sure (using this reguarly) Set-AzContext -SubscriptionId $​SubscriptionId ## $SubscriptionId is a subscription ID where is the  Note that you’ll want to add the “Download Key Vault Secrets” task that appears first – this is the official task from Microsoft. Then, click on the new “Azure Key Vault” task you just added to your pipeline, and set a display name. Choose the Azure subscription in which you created your key vault, and then select from the “Key vault” dropdown list the name of the key vault you stored your secrets in.

Add/get secret to Azure Keyvault with Azure powershell task in , How to inject Azure Key Vault secrets in the Azure DevOps CI/CD pipelines Please note that “Get, List” permissions are required to retrieve secrets so you will have to Let do the next step - create PowerShell script to replace connection We have to add one more task to the build pipeline definition. Azure DevOps Variable Group to connect to an Azure Key Vault from your build tasks. It will ask you to Authorize the connection so that Azure DevOps has permission to Get and List secrets from the given vault. Once you've clicked " Authorize " you should see an empty section of Variables.

How to inject Azure Key Vault secrets in the Azure DevOps CI/CD , Add the Build Pipeline permissions to the Key Vault. Before this will in the DevOps build. Use the Key Vault in an Azure CLI Powershell script. Done - secret from the Azure Key Vault are now available for us in the build pipeline. Let do the next step - create PowerShell script to replace connection string in the “AppSettings.json” file with the secrets obtained from the Key Vault. Add “Replace Tasks” task for the credentials replacement and use secrets from the KeyVault

Comments
  • Tried out your answer but this does gave me the exact same error :( Thnx for answering
  • Tried out your answer and this seemed to work at first. But when I tried to set or even get a keyvault secret I got an unauthorized error message, So I guess with the Add-AzureRmAccount I've logged into a different user somehow. This is my code $context = Get-AzureRmContext Add-AzureRmAccount -AccountId $context.Account.Id -AccessToken $context.Account.AccessToken -KeyVaultAccessToken $context.Account.AccessToken