Ken Muse

Conditional Build and Release Tasks in VSTS

One of the most overlooked features in VSTS is the ability to determine whether a task will be executed using custom conditions. What are custom conditions? It’s the ability to specify a short expression which evaluates to a boolean value. If the result is true, the task will be executed. If the value is false, the task is ignored. For example, let’s take this expression:

This expression evaluates the built-in variable Build.Reason to determine if the task is executing the build as part of a pull request branch policy. If the build status is currently failed and the build was triggered by a pull request, the task will execute. In all other cases, the task will be skipped.

Custom conditions also allow us to also define tasks which will only execute if a specific variable is provided. This allows us to create a build definition in which some of the tasks are ignored if we don’t have all of the values we need. This functionality can be paired with Task Groups to allow you to create complex build-time logic. For example, perhaps we have a set of tasks that will only execute if an Application Insights API Key (AppInsightsKey) has been provided. In that case, we can compose an expression like the following:

To make this work, we will utilize the value string variable. When we put this value into a boolean expression, the string will be converted to a boolean. VSTS uses a simple rule for this conversion — an empty string is converted to false and a string with a value will convert to true. This expression will therefore evaluate to true if the specified variable has any value. The always() function simple returns true, even if the task was cancelled.

Any variable exposed to our tasks is usable as part of a custom condition. This means that we can examine user-defined variables as well as the variables that are passed into the build or release tasks by VSTS. Consequently, we can alter the build process dynamically based on the status or characteristics of the build itself. As an example, this can allow a single build definition to be streamlined for use in a pull request.

The conditional expression feature supports a number of additional functions which will apply conditional logic, including contains, in, equals, xor, and startsWith. You can learn more about this functionality (with samples) on Microsoft Docs.