Skip to content
Latchkey

How to Conditionally Run a Job or Stage in Azure Pipelines

Azure Pipelines gates a stage, job, or step with the condition: key and expression functions like eq, and, and succeeded.

Set condition: to an expression. By default a stage runs only if previous ones succeeded; override that with explicit functions to branch on refs, variables, or status.

Run deploy only on main

Combine succeeded() with a branch check so deploy runs only on a successful main build.

azure-pipelines.yml
stages:
  - stage: build
    jobs:
      - job: build
        steps: [ { script: npm run build } ]
  - stage: deploy
    dependsOn: build
    condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
    jobs:
      - job: deploy
        steps: [ { script: ./deploy.sh } ]

Gotchas

  • A custom condition: replaces the default succeeded() - include succeeded() yourself or the stage may run after failures.
  • Use variables['Build.SourceBranch'] (full ref like refs/heads/main), not just the short branch name.
  • Conditions are evaluated as expressions; wrap variable comparisons in eq()/ne() rather than ==.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →