Set Pull Request polices based on raising user(s) - azure-devops

I want to assign required approvers based on who raises a PR and not what the PR is on.
I have a set of repos that is maintained by multiple teams. I want to have a team be automatically added as required reviewers based on the user making the PR.
Is this even possible?

Is this even possible?
It's possible. But the process would be very complex since Azure Devops doesn't have such out-of-box feature, so we have to use Build Validation/Rest API/PS to achieve what you want.
1.Create a Classic Build pipeline with PS task.
2.Add build validation in branch policy. So this pipeline will run first if anyone raises a PR.
3.If one pipeline is triggered by PR, we can access the variables like $(Build.Repository.ID),$(Build.RequestedFor)(the user making the PR),$(Build.RequestedForEmail)(the user's email). See predefined variables.
4.Use Teams-Get to get list of teams in current project. You now have the TeamIDs, you now know the corresponding TeamIDs the user belongs to.
5.Use powershell switch or if statement to dynamically define the team the user belongs to.
switch ("$(Build.RequestedFor)")
{
"User1" {$TeamID="xxxx"; Break}
"User2" {$TeamID="xxxx"; Break}
"User3" {$TeamID="xxxx"; Break}
Default {
"No matches"
}
}
6.Use Configurations-List to list the ConfigurationIDs in this project. (You may also need to determine the correct ConfigurationID by SourceRepo and SourceBranch)
7.Then use Configuration-Update to update the branch policy to define required approvers dynamically.
The request body would look like this:
{
"isEnabled": true,
"isBlocking": true,
"type": {
"id": "fd2167ab-b0be-447a-8ec8-39368250530e"
},
"settings": {
"requiredReviewerIds": [
"{replace it with corresponding TeamID}"
],
"filenamePatterns": [],
"addedFilesOnly": false,
"scope": [
{
"repositoryId": "{replace it with your repoID in step3}",
"refName": "refs/heads/master",
"matchKind": "exact"
}
]
}
}
You can do step5 and step7 in same PS task.

Related

Azure DevOps - Unable to Create Var Group using Azure DevOps API and Auth Token

Requirements: We would like to create a Variable Group (along with some variables) in a given Project.
Option1: We are able to create a new Variable Group successfully
when we create a request via PostMan using PAT Token which has FULL access.
Option2: Our end goal is to invoke the ADO Rest API in the Web App which uses
OAuth. When the end user logs in and make a call (pls see the input
details below) we are getting '401 Un Authorized - The user is not authorized to access this resource.' error. The Web App's application has the Variable Groups manage scope as shown below.
TroubleShooting: As part of troubleshooting, for Option1 which uses PAT (with full access) in Postman, we have updated the permissions of the PAT to just have Create, Read and Manage Var Groups as shown below.
Now, even the Option1 is not working after making the PAT to have Custom Defined access.
Are we missing something?
Postman Details:
URL: https://dev.azure.com/myorgname/_apis/distributedtask/variablegroups?api-version=6.0-preview.2
Verb: Post
Headers: Authorization: Basic
Body:
{
"name": "This is ignored",
"description": "This is ignored",
"type": "Vsts",
"variables": {
"BuildConfiguration": {
"value": "Release"
}
},
"variableGroupProjectReferences": [
{
"name": "VarGroup",
"description": "The variable group to store the information about the variables using in the Pipeline",
"projectReference": {
"id": "#ProjectId#",
"name": "#ProjectName#"
}
}
]
}
I can also reproduce your issue with option 1, not only Read, create, & manage for Variable Groups, even I select all the scopes via Custom defined, it still does not work.
According to this doc - https://learn.microsoft.com/en-us/azure/devops/organizations/accounts/manage-pats-with-policies-for-administrators?view=azure-devops#restrict-creation-of-full-scoped-pats
Some of our public APIs are currently unassociated with a PAT scope, and can therefore only be used with “full-scoped” PATs. Because of this, restricting the creation of full-scoped PATs might block some workflows. We're working to identify and document the affected APIs and eventually associate them with the appropriate scope. For now, these workflows can be unblocked by using the allow list.
I believe this should be the reason for this issue, there may be some additional permissions to create variable groups. For option 2, there may be a similar cause.
So in this case, you may need to use the Full access PAT temporarily, as mentioned in the doc We're working to identify and document the affected APIs and eventually associate them with the appropriate scope.

Provisioning users in Azure Devops and creating tasks for them

We have a bulk import mechanism where we add users to ADO and create tasks assigned to them using the user Entitlements API. We have observed that after initially adding the users to ADO, any tasks created for them via the API does not resolve the user's identity correctly. Any subsequent tasks are created correctly and show the users resolved.
Any task's 'Assigned To field should be an Identity -
Fname Lname alias#email.com
but for the first upload, it is just alias#email.com.
Is there a way to do this so that this works, even for first upload?
I have tested it in my side and I can assign the new user for the work item by api.
And you should check if the new account has the right permission.
These are my json test:
[
{
"op": "add",
"path": "/fields/System.Title",
"from": null,
"value": "xxx"
},
{
"op" : "add",
"path": "/fields/System.AssignedTo",
"from": null,
"value": "xxx#outlook.com"
}
]
I can use it under postman. Also, you could use the e-mail or user name under value.
Besides, you could share the used tool and the steps about your operation with us to help us troubleshoot your issue more quickly.

Dynamically set person who queues a release to approver in Azure DevOps?

I have a two stage release:
Stage 1 creates a test DB
pre-deploy approval on Stage 2
Stage 2 test DB just created is destroyed
This setup allows devs time to test changes before approving automated cleanup.
My question is, is it possible to dynamically set the pre-deploy approval (step #2 above) to the user who submitted the release? If not, perhaps there is a better way to pause the release until the submitter manually allows it to continue?
For this issue , you can try to set approver through the Definitions - Update rest api.
You can add approver in "preDeployApprovals" argument. For example:
"preDeployApprovals": {
"approvals": [{
"approver": {
"id": "9f723013-a332-64e5-aea9-6e3ebxxxxx",
"displayName": "hughl01",
"isContainer": false
},
"isAutomated": false,
"isNotificationOn": false,
"rank": 1,
"id": 0
}]
},
Then you can set the pre-deploy approval to the user who submitted the release through pre-defined variables:
Release.RequestedFor The display name of identity that triggered
the release.
Release.RequestedForId The ID of identity that triggered the
release.
In the request body ,you can use $(Release.RequestedFor) to dynamically get the name of the user who triggered the release and use it as the name of approver. The same goes for $(Release.RequestedForId).
Here are some references for you:
set approver with PowerShell
release pre-defined variables

Azure DevOps REST APIs FOR SWIMLANE

I am trying to integrate Servicenow with Azure Devops Board to create/update etc etc on a work item using REST APIs
I was successful in creating and updating lot of things on the workitems
I am not able to find an API which tells the workitem to fall in a specific Swimlane
If you look in to the image I have attached, which has a default swimlane(test) and custom ones... so H have an api which moves it from "ToDo" to "Doing", but if you notice there multiple "Doing" as there are different swimlanes, so can anyone please help what the trick is or an API which tells the workitem to fall in a specific SwimLane
I did some research and found "System.BoardLane" I did use that in post and patch
ERROR:
{
"$id": "1",
"customProperties": {
"ReferenceName": null
},
"innerException": null,
"message": "TF401326: Invalid field status 'ReadOnly' for field 'System.BoardLane'.",
"typeName": "Microsoft.TeamFoundation.WorkItemTracking.Server.WorkItemFieldInvalidException, Microsoft.TeamFoundation.WorkItemTracking.Server",
"typeKey": "WorkItemFieldInvalidException",
"errorCode": 600171,
"eventId": 3200
}
then I used operation "op" :"move"
ERROR:
{
"$id": "1",
"innerException": null,
"message": "Move/Copy is not implemented.",
"typeName": "Microsoft.VisualStudio.Services.WebApi.Patch.PatchOperationFailedException, Microsoft.VisualStudio.Services.WebApi",
"typeKey": "PatchOperationFailedException",
"errorCode": 0,
"eventId": 3000
}
Azure DevOps REST APIs FOR SWIMLANE
In fact, you were very close to the correct answer.
The first error you faced: TF401326: Invalid field status 'ReadOnly' for field 'System.BoardLane' has indicate that if you want to modify the SwimLane by updating the System.BoardLane field via API, we does not allow that because of its read-only.
(For those fields, not only System.BoardLane is read-only, but also the System.BoardColumn)
This is by designed.
In order to update the SwimLane, here you need to update the extension fields instead of System fields via the API.
Step1:
Call the Get - Boards API to get the information about the Board. In its response body, the extension field names will display under fields -> rowField.
Sample:
GET https://dev.azure.com/{org name}/{project name}/{team name}/_apis/work/boards/Stories?api-version=5.1
The reference names for these extension fields will include a GUID that is unique for the board(e.g. WEF_6623ED31B8E04C778FB1129D3239B1A7_Kanban.Lane).
Step2:
Call the Update - Work Items API, using the field names you got above as the path (e.g. /fields/WEF_6623ED31B8E04C778FB1129D3239B1A7_Kanban.Lane) and input the lane value as the name of the row you want to move the item into:
Sample:
PATCH https://dev.azure.com/{org name}/{project name}/_apis/wit/workitems/{WIT id}?api-version=5.1
Request body:
[
{
"op": "add",
"path": "/fields/WEF_6623ED31B8E04C778FB1129D3239B1A7_Kanban.Lane",
"from": null,
"value": "Lane for product team"
}
]
Lane for product team is one of the Swimlane.
Now, you would see that the work item moved into the corresponding lane you specified.
Note: The GUID of the extension fields is unique for the board. Different boards has different extension fileds GUID value.
The swimlane that is used is based on the status of the workitem (I believe the field you want is System.Status) If you update that value of the workitem, it should move the workitem into the appropriate swimlane.
You can configure your team's board settings to map statuses to the swim lanes you want. If you are using an standard board process, then it should be pretty straightforward mapping between statuses and swim lanes, but if you have customized work items you will need to apply that logic to your code(IE this new item should be in a status of X to show as doing)

Passing 'settable at queue time' build pipeline variables through REST api [duplicate]

I would like to start a Azure Pipelines build through the REST API. There is an API for queuing builds but I couldn't find a way to define variables.
The accepted answer does not really answers the question when you need to set a value at queue time.
The solution is actually pretty simple you just have to add a parameters field to the json payload. The content should be a json string (not directly an object) containing the parameters
Ex :
{
"parameters": "{\"ReleaseNumber\": \"1.0.50\", \"AnotherParameter\": \"a value\"}",
"definition": {
"id": 2
}
}
EDIT : This feature is now properly documented as an optional stringified dictionary. See https://www.visualstudio.com/fr-fr/docs/integrate/api/build/builds#queue-a-build
Variables are included in definitions, you can update your build definition to set the variables via build-definition api first and then queue the build.
Following is the variable section get via build-definition api:
"variables": {
"system.debug": {
"value": "false",
"allowOverride": true
},
"BuildConfiguration": {
"value": "release",
"allowOverride": true
},
"BuildPlatform": {
"value": "any cpu",
"allowOverride": true
}
},
For anyone having problems with this (I did), there is a difference in APIs used since the accepted answer (which to me didn't work at all). But following Cyprien Autexier's advice, I took a look under the hood (Firefox Dev Tools) and I noticed the portal does not use the Builds API anymore. It uses the Pipelines one (https://learn.microsoft.com/en-us/rest/api/azure/devops/pipelines/runs/run-pipeline?view=azure-devops-rest-6.1). With this, worked flawlessly.
For anyone looking this, I was able to make it work with 'templateParameters', which allow you to send an Object instead of a String on version 7.1.
Method: POST
URL: https://dev.azure.com/{organization}/{project}/_apis/build/builds?api-version=7.1-preview.7
Body: JSON example:
{
"sourceBranch":"Development",
"definition": {
"id": 5
}
"templateParameters": {
"PARAMETER1": "value1",
"parameter2": "valuex"
}
}
Docs: https://learn.microsoft.com/en-us/rest/api/azure/devops/build/builds/queue?view=azure-devops-rest-7.1
Seems it works with 5.1. All you need to do is define the variables you pass in as parameters within the pipeline variables and ensure the checkbox "Settable at queue time" is checked. If you have same variable in any library make sure you remove those references as library variables are seen to override those set via API.
Note I use Azure Devops Server 2019
API: https://learn.microsoft.com/en-us/rest/api/azure/devops/build/builds/queue?view=azure-devops-rest-5.1
Navigating to set variables: Edit the YAML pipeline -->click on the 3 dots near "Run" button --> Variables --> Variables TAB
Hope it helps someone