Detect a build requested by pull request and one run by any updates to the PR

Viewed 123

I currently have a task that I intend to run only once when a PR is created. Any pipeline runs due to new commits should not trigger the task. I was wondering if there is a way to detect the runs triggered by changes to code in the PR? When I use the predefined variable $(Build.Reason) I get back PullRequest for both builds(One triggered when PR is created and other when updates are made to PR).

This is what I have in my pipeline and I have enabled build validation for my pipeline.

trigger:
- master
pr:
- master
1 Answers

I don't think there's a way to differentiate the "PR is created" and "PR is updated" build reasons based only on the predefined variables.

However, you can choose a different route depending on what this task you should only run once is. If it is something that can be wrapped into a service with a public endpoint, you can try leveraging the Webhooks.

So, if this is an option for you, try the following:

  • wrap the functionality required to run only on the PR creation into the service with the public endpoint
  • create a webhook, choose "Pull request created" event type and enter the public URL of your service

As a result, your build logic won't branch depending on the build reason, and that specific action will be run by the webhook.

I understand it all sounds like a hack and unnecessary complexity, but it's up to you to decide whether it fits your case. At least, this is possible technically.

Related