When you set the build as the Build validation in Pull Request, the build will execute before completing the Pull Request. So it will not meet your requirements.
You could refer to this doc about Branch Policy.
Any idea of how to add a tag conditionally to the merged-commit?
Since the variable System.PullRequest.TargetBranch
and System.PullRequest.SourceBranch
only exist in the Pull Request Trigger Build, you could try the following Settings to set the pipeline. Create two pipelines: Pipeline 1 and Pipeline 2.
In Pipeline 1 , you could set the condition and use Rest API to trigger the pipeline 2.
In Pipeline 2, you could add an Environment in the Pipeline 2, and the Environment contains the check: Invoke Rest API to check the status of the Pull Request. If the API response meets the requirements(Pull Reuqest Status is completed), it will run the git command to add tag.
Here is my sample:
Pipeline 1:
trigger: none
pool:
vmImage: 'windows-latest'
jobs:
- job: Tag_As_Hotfix
condition: and( eq(variables['System.PullRequest.TargetBranch'],'refs/heads/master'), startsWith(variables['System.PullRequest.SourceBranch'], 'refs/heads/test'))
steps:
- task: PowerShell@2
inputs:
targetType: 'inline'
script: |
$token = "PAT"
$url="https://dev.azure.com/{Org}/{Project}/_apis/distributedtask/variablegroups/{VariableGroup ID}?api-version=5.0-preview.1"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$JSON = @'
{
"variables": {
"id": {
"value": "$(SYSTEM.PULLREQUEST.PULLREQUESTID)"
}
},
"type": "Vsts",
"name": "New variable group 16-Nov"
}
'@
$response = Invoke-RestMethod -Uri $url -Headers @{Authorization = "Basic $token"} -Method PUT -Body $JSON -ContentType application/json
- task: PowerShell@2
inputs:
targetType: 'inline'
script: |
$token = "PAT"
$url="https://dev.azure.com/{ORG}/{Project}/_apis/build/builds?api-version=5.0"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$JSON = @'
{
"definition": {
"id": BuilddefinitionID
}
}
'@
$response = Invoke-RestMethod -Uri $url -Headers @{Authorization = "Basic $token"} -Method Post -Body $JSON -ContentType application/json
Note: You need to create a Variable Group to save the Pull Request ID. This id could be used in the Invoke Rest API check
.
Pipeline2:
trigger:
- none
pool:
vmImage: 'windows-latest'
stages:
- stage: deploy
jobs:
- deployment: DeployWeb
displayName: deploy Web App
environment: 'API Test'
strategy:
runOnce:
deploy:
steps:
- script: |
git tag hotfix
git push origin master
Environment: Pipelines -> Environemnts-> Approvals and checks -> Invoke Rest API

Variable Group:

Workflow
Create Pull Request -> Trigger Pipeline 1 -> Trigger Pipeline2 and Update the ID in Variable Group -> Pipleline 2 check the Pull Request Status -> Run the command to Add Tag.