I have built up a pipeline with a powershell task to create new secrets in Azure Key Vault. The same key vault is linked with Azure DevOps variable group (pipelines / library / variable group).
I already added few keys manually, but I want it to be able to add new secrets,which I create in Azure Key vault during the pipeline deployment also to the variable group.
Do I have to make use of REST API?
https://learn.microsoft.com/en-us/rest/api/azure/devops/distributedtask/variablegroups/add?view=azure-devops-rest-7.1
Or can I make use of Powershell or something else?
2
Answers
If you want to set the pipeline to automatically add the new secrets into the variable group, you need to call the following Azure DevOps REST API in the pipeline job:
Call the API "Variablegroups – Get" to get the response body (JSON) of the variable group you want to update. From the response body, you can see it contains the contents like as below.
The "
<SecVar01>
" and "<SecVar02>
" are the actual names of the secrets that have been added into the variable group.Update the response body by inserting the new secret object as a member of the "
variables
" node. For example, add new secret "<SecVar03>
".Then call the API "Variablegroups – Update" and pass the updated JSON body above as the Request Body of this API. Once this API call is succeeded, the new secret "
<SecVar03>
" is added into the variable group.EDIT:
Below I will share you with a sample of how to call the related REST API to add secret from Azure Key Vault to the variable group using PowerShell script in Azure Pipelines.
Since we run the PowerShell script in pipeline, we can use "
System.AccessToken
" instead of a user’s PAT as the authorization on the API call. To use this token to update the variable group, you need to ensure that you have assigned theAdministrator
role to the following two build identities on the Security hub of the variable group. For more details, you can see "Job access tokens".Project Collection Build Service ({Organization Name})
{Project Name} Build Service ({Organization Name})
The PowerShell script looks like below.
Call the PowerShell script in Pipeline.
{organization}
with the actual name of your Azure DevOps organization.{project}
with the actual name of the project.{groupId}
with the actual id of the variable group.{secretName}
with the actual name of the secret needs to add from Azure Key Vault to the variable group.As a workaround .. You may use AzureKeyVault to receive all secrets. Then you may use them in your pipeline.