How to reference System variables when selecting a variable group in Azure Devops

102 Views Asked by At

I have a Build Validation Pipeline, defined by a yaml file, which runs when a pull request is created to a specific branch. I am trying to reference the System.PullRequest.targetBranchName predefined variable when selecting a variable group at the top of the yaml:

variables:
  - ${{ if eq(variables['System.PullRequest.targetBranchName'], 'QA') }}:
      - group: "Pipeline_Variables_QA"

However, the variable group is not selected - variables are not found later in the pipeline.

If I substitute that if statement for this one:

  - ${{ if eq(variables['Build.Reason'], 'PullRequest') }}:
      - group: "Pipeline_Variables_QA"

It succeeds. The Build.Reason variable has a value of PullRequest when referenced like this but the System.PullRequest.targetBranchName doesn't seem to have any value.

if I assign the variable to another variable:

variables:
  - name: targetBranchName
    value: variables['System.PullRequest.targetBranchName']

and then in a script echo targetBranchName, I get the value as 'QA'.

Where am I going wrong here? How should I be referencing the System variables?

Thanks in advance.

I have tried several different ways of adding the variable:

  - ${{ if eq(variables.System.PullRequest.targetBranchName, 'QA') }}:
      - group: "Pipeline_Variables_QA"
  - ${{ if eq([variables['System.PullRequest.targetBranchName']], 'QA') }}:
      - group: "Pipeline_Variables_QA"
1

There are 1 best solutions below

1
On BEST ANSWER

This is by design. The expression syntax ${{}} is for compile time. The variable Build.Reason can be got at compile time, so the pipeline works when you use it. But the variable System.PullRequest.targetBranchName is got at the runtime and is empty at compile time. See more info about expression from doc Expressions.

In a pipeline, template expression variables ${{ variables.var }} get processed at compile time, before runtime starts. Macro syntax variables $(var) get processed during runtime before a task runs. Runtime expressions $[variables.var] also get processed during runtime. So you can echo the value of System.PullRequest.targetBranchName in the task. See more info from Understand variable syntax.