Reputation: 81
I'm executing a pipeline flow after creating a PR and I need to get Pull Request ID after I click the complete button.
I'm using $(System.PullRequest.PullRequestId) to fetch the value, but it is always an empty value and gives the error output "System.PullRequest.PullRequestId: command not found"
Create a simple classical pipeline like below and it needs to be called in Branch Policies -> Status Check.
Note: With the same variable $(System.PullRequest.PullRequestId) I'm able to get the ID before the completion i.e., when PR is in an active state.
Upvotes: 5
Views: 11756
Reputation: 11
The only way I could this is by extracting PR ID from merge commit message using regex expression.
Merge commit message is available using $(Build.SourceVersionMessage)
environment variable in CI (Yes CI after merging the PR) build and then I used Merged PR (\d*):.*
regex expression to extract the PR Id.
I see the merge commit message is generally generated as Merged PR [PR ID]: [PR Title]
e.g. Merged PR 123456: My first PR in the world of coding :)
Upvotes: 1
Reputation: 41745
Ad @CodeCaster said in the comment, the variable $(System.PullRequest.PullRequestId)
is initialized only if the build ran because of a Git PR affected by a branch policy.
But, you can get the last completed PR ID with small PS script via the Rest API:
$header = @{ Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN" }
$url = "$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_apis/git/repositories/$(Build.Repository.Name)/pullrequests/?searchCriteria.status=3&top=50&searchCriteria.targetRefName=refs/heads/master&api-version=6.1"
$pullRequests = Invoke-RestMethod -Uri $url -Method Get -Headers $header -ContentType application/json
Write-Host "Last PR completed to master is: $($pullRequests.value[0].pullRequestId)"
Just replace the master
in the $url
with your target branch name.
Don't forget to enable the access token if you use the Classic editor or add the token to your YAML task.
Upvotes: 3