Reuse Build Definition for Pull Request Validation using Custom Conditions for Azure Pipelines

Reuse Build Definition for Pull Request Validation using Custom Conditions for Azure Pipelines

When you want to use a build definition as a build validation step in VSTS branch policies and use it as a part of the code review process you would be executing tasks in the build definition that is not needed for pull request validation. For example, file copy tasks that are not part of the build process, artifact publishing tasks (if the pull request build is not used for deploying the application) are some of the things that you may want to exclude from executing to save time and speed up the pull request build validation time.

To accomplish this what I used to do was to have a minimal build definition that is only used for pull request validation. This works fine but this is cumbersome especially if you have many build definitions to manage. For example, my team is creating and publishing close to 30 NuGet packages and to have a pull request build for each is not practical.

But you can reuse a single build definition for multiple purposes using Custom Conditions for VSTS tasks. This was released sometime back, in March 2017 and its available for build and release tasks. You can add a custom condition by expanding the Control Options section of the build/release task and selecting Custom Conditions from the Run this task drop down menu. Then you can enter the custom condition you want.

For this example, I will use the pull request scenario. And we would want to add the following condition as the custom condition

and(succeeded(), ne(variables['Build.Reason'], 'PullRequest'))

What this does is only execute the task if the VSTS Job Status is successful and the reason for the build is not equal to PullRequest. The Build.Reason is a built-in variable for VSTS. So the task would look something like this.

1 custom conditions applied to tasks

And When you trigger the build from a pull request, these 2 tasks that I have added the custom condition will not execute. And the build result would something like this.

2 tasks with custom conditions skipped

So, you can see the Copy ARM Template task and Publish Build Artifact tasks were not executed. So you can see the custom conditions are a great way to conditionally execute build/release tasks enabling you to reuse build/release definitions in different scenarios.

You Might Also Like
Comments