tubatanne
tubatanne

Reputation: 103

How to use variables as conditionals in steps of Azure Pipelines?

Azure Pipelines defines variables and conditions for the use in different pipeline tasks, steps and soon. When defining the following YAML pipeline, the step ReleaseOnlyScript should only be executed when the combined condition evaluated by the variable isValidReleaseBuild is true. In the Azure Pipeline DevOps Site, a variable BuildTypeis defined and set to release.

variables:
  - name: isValidReleaseBuild
    value: $[and(eq(variables['BuildType'], 'release'), startsWith(variables['Build.SourceBranch'], 'refs/tags/v'))]

steps:
  - script: |
      echo "BuildType: $(BuildType)"
      echo "SourceBranch: $(Build.SourceBranch)"
      echo "ReleaseBuild: $(isValidReleaseBuild)"
    displayName: 'Buildinfo'
  - ${{ if eq(variables['isValidReleaseBuild'], true) }}:
    - script: |
        echo "YEAH its a Release!"
      displayName: 'ReleaseOnlyScript'

When running the pipeline, only the script BuildInfo is executed with the following output.

BuildType: release
SourceBranch: refs/tags/v1.0.0
ReleaseBuild: True

Why is the ReleaseOnlyScript not executed?

Update: Thx to Alex AIT's answer, I modified the pipeline as follows and it works now as expected.

variables:
  - name: isValidReleaseBuild
    value: $[and(eq(variables['BuildType'], 'release'), startsWith(variables['Build.SourceBranch'], 'refs/tags/v'))]

jobs:
  - job: check_cicd
    steps:
      - script: |
          echo "BuildType: $(BuildType)"
          echo "SourceBranch: $(Build.SourceBranch)"
          echo "ReleaseBuild: $(isValidReleaseBuild)"
          if [ "$(isValidReleaseBuild)" = "True" ]; then
            echo "##vso[task.setvariable variable=ValidBuild;isOutput=true]True"
          else
            echo "##vso[task.setvariable variable=ValidBuild;isOutput=true]False"
          fi
        name: buildinfo
  - job: release_cicd
    dependsOn: check_cicd
    condition: eq(dependencies.check_cicd.outputs['buildinfo.ValidBuild'], 'True')
    steps:
      - template: build-release.yml

Upvotes: 10

Views: 25525

Answers (1)

Alex
Alex

Reputation: 18556

https://learn.microsoft.com/en-us/azure/devops/pipelines/process/conditions?view=azure-devops&tabs=yaml

You have to use condition within your step, not an expression at the beginning.

parameters:
  doThing: false

steps:
- script: echo I did a thing
  condition: and(succeeded(), eq('${{ parameters.doThing }}', true))

Upvotes: 14

Related Questions