Kaspar H
Kaspar H

Reputation: 179

How to use runtime defined variable in conditional expression in Azure Pipelines

I'm trying to use the build number of the pipeline in a conditional to determine which task to run.

Inspired by this example in the ADO expressions FAQ, I set a variable to the minor number of the build number:

- script: |
    minor_run=$(echo $BUILD_BUILDNUMBER | cut -d '.' -f2)
    echo "Minor run number: $minor_run"
    echo "##vso[task.setvariable variable=minor]$minor_run"

This prints out the correct minor number, let's say Minor run number: 14 for the following examples.

If I want to print out the minor, I can do it like this

script: "echo $minor"

Now I want to use this in a conditional. I'm trying something like this:

- ${{ if eq(variables.minor, 14)  }}:
  - script: "echo first if worked"
- ${{ elseif eq(variables['minor'], 14)  }}:
  - script: "echo second if worked"
- ${{ else }}:
  - script: "echo neither worked"

I always get to the else part. I have tried evaluating against '14' as well, but same result. I have also tried evaluating $minor, $(minor), and just minor, but that causes the pipeline to fail entirely.

What's the correct way to use a defined variable in a conditional?

Upvotes: 0

Views: 2173

Answers (1)

Antonia Wu-MSFT
Antonia Wu-MSFT

Reputation: 559

I see you set two conditions all to minor value '14'. Then you could use condition to set two scenarios when minor value is 14 and not.

You could use condition syntax as this.

steps:
- bash: |
    MAJOR_RUN=$(echo $BUILD_BUILDNUMBER | cut -d '.' -f1)
    echo "This is the major run number: $MAJOR_RUN"
    echo "##vso[task.setvariable variable=major]$MAJOR_RUN"

    MINOR_RUN=$(echo $BUILD_BUILDNUMBER | cut -d '.' -f2)
    echo "This is the minor run number: $MINOR_RUN"
    echo "##vso[task.setvariable variable=minor]$MINOR_RUN"

- script: "echo first if worked"
  condition: eq(variables.minor, 8)
- script: "echo neither worked"
  condition: ne(variables.minor, 8)

Test on my side, if you want to use if syntax, you need to set specific value in pipeline variables part like this. I hope this could do some help.

Upvotes: 1

Related Questions