Posted on Leave a comment

Conditional execution for stage – Azure DevOps

Conditions on Azure DevOps provide the flexibility to execute logic based on different environments and setups. You can use the template expression to execute a specific stage based on a variable or parameter that is provided from user input.

Lets take for example the below scenario. We need to deploy on two different environments the uat and production. Logic for these environments is included in the template files that are located inside the repository under pipelines/templates folder.

Based on user input only the stage for the selected environment will be executed.

main.yml

trigger:
- none

parameters:
  - name: environment
    type: string
    values:
      - production
      - uat

pool:
  vmImage: ubuntu-latest

stages: 

- ${{ if eq(parameters.environment, 'production') }}:
  - template: pipelines/templates/production.yml
- ${{ elseif eq(parameters.environment, 'uat') }}:
  - template: pipelines/templates/uat.yml

production.yml

stages:
- stage: production
  displayName: running production deployment
  jobs:    
  - job: job1
    steps:
    - script: echo "inside production environment"  
      displayName: print message production task

uat.yml

stages:
- stage: uat
  displayName: running uat deployment
  jobs:    
  - job: job1
    steps:
      - script: echo "inside uat environment"
        displayName: print message uat task

Video tutorial on Youtube: