issue with ${{ if }} syntax along with or conditional expression in azure pipelines

Viewed 86

I am working on Azure DevOps YAML Pipelines and trying to do something like -

if project = proj1 or project = proj2: run some commands.

if project = proj3: run some other commands.

Snippet of code:

- ${{ if or(eq(parameters.project, 'proj1'), eq(parameters.project, 'proj2')) }}: # 1st if
  - bash: |
      echo "Hello"
    name: hello
- ${{ if eq(parameters.project, 'proj3') }}: # 2nd if
  - bash: |
      echo "Hi"
    name: hi

Now, I have been using 2nd if conditions for quite some time and that is working flawlessly. The issue is with 1st if condition. Even when correct parameter is passed, the control wont go into that code block.

2 Answers

I tested this with following code:

parameters:
- name: project
  type: string
  default: proj1
  values:
  - proj1
  - proj2
  - proj3

trigger: none

steps:
- ${{ if or(eq(parameters.project, 'proj1'), eq(parameters.project, 'proj2')) }}: # 1st if
  - bash: |
      echo "Hello"
    name: hello
- ${{ if eq(parameters.project, 'proj3') }}: # 2nd if
  - bash: |
      echo "Hi"
    name: hi

and it works as expected. Can you explain how you setp values for project?

enter image description here

In September 2021 Azure DevOps Service update, we have a new syntax for the same and it's better to use that.

Explaining that with my original example -

- ${{ if or(eq(parameters.project, 'proj1'), eq(parameters.project, 'proj2')) }}: # if
  - bash: |
      echo "Hello"
    name: hello
- ${{ elseif eq(parameters.project, 'proj3') }}: # elseif
  - bash: |
      echo "Hi"
    name: hi
- ${{ else }}: # else
  - bash: |
      echo "Hey"
    name: hey

The advantage over previous syntax is that instead of expanding and comparing if condition every time, this will short circuit on first true match and only move to elseif or else if all previous conditions are false.

It might also help in speeding up the pipeline (some fraction of a second).

I have completely migrated my pipelines to new syntax. Microsoft may/may not discontinue old syntax in near future so it is advised to migrate to new one.

Related