Amateur
Amateur

Reputation: 407

Azure devops optional stage

I have a yaml pipeline that builds and deploys a project. it deploys to dev & tst. But i dont always want to deploy to tst. at the moment i have solved this with approvals. when the dev stage finishes the pipeline waits for approval.

this introduces some problems:

Upvotes: 9

Views: 4565

Answers (1)

danielorn
danielorn

Reputation: 6167

If there is a well defined way how to determine whether to run the tst stage or not, you can either specify a custom condition on the stage or conditionally include the stage using an expression

Specify a condition

From the docs:

You can specify the conditions under which each stage, job, or step runs. By default, a job or stage runs if it does not depend on any other job or stage, or if all of the jobs or stages that it depends on have completed and succeeded.

There are a number of ways you can customize this behavior, either by built in or custom defined conditions, for example, to run tun the tst stage only if the branch is main:

stages:
- stage: dev
  jobs:
  - job: dev1
    steps:
      - script: echo Hello from dev!

- stage: tst
  condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
  jobs:
  - job: tst1
    steps:
      - script: echo Hello From tst!

The tst stage will still be visible when you open the pipeline run, it will be marked as skipped

The condition under the tst stage can be altered to fit your need (it can include both variables, parameters and even output from previous stages.

Conditional expression

From the docs:

You can use if, elseif, and else clauses to conditionally assign variable values or set inputs for tasks. You can also conditionally run a step when a condition is met.

Conditional insertion only works with template syntax, which is evaluated when the pipeline yaml is compiled (i.e before the pipeline starts). Thus it cannot evaluate output of previous steps. In the below example the tst stage is completely removed from the pipeline run when the pipeline is instantiated (and the template compiled) if the branch is not main

stages:
- stage: dev
  jobs:
  - job: dev1
    steps:
      - script: echo Hello from dev!
- ${{ if eq(variables['Build.SourceBranch'], 'refs/heads/main') }}:
  - stage: tst
    jobs:
    - job: tst1
      steps:
        - script: echo Hello From tst!

Upvotes: 1

Related Questions