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 defaultsucceeded()- includesucceeded()yourself or the stage may run after failures. - Use
variables['Build.SourceBranch'](full ref likerefs/heads/main), not just the short branch name. - Conditions are evaluated as expressions; wrap variable comparisons in
eq()/ne()rather than==.
Related guides
How to Conditionally Skip a Job in GitHub ActionsConditionally run or skip a GitHub Actions job with the if: key and expressions - branch checks, event checks…
How to Run a Pipeline Only on Changed Paths in Azure PipelinesRun an Azure Pipeline only when certain files change using trigger paths include/exclude, and gate stages wit…