Sunday, May 26, 2024

Run YAML Pipeline Stages Based on Dynamic Variable Values

YAML pipeline conditions can be utilized to generate pipelines that meet various criteria, such as dependencies between stages and determining whether a stage should be run or not. In this blog post, we will learn how to run stages based on dynamically generated variables.

Pre-requisites: Azure DevOps Account

1. The following pipeline consists of two stages called StageA and StageB. StageB depends on StageA.

2. Dynamically assign a value to the variable 'dependantstageshouldrun' as below

 Write-Host "##vso[task.setvariable variable=dependantstageshouldrun;isOutput=true]true"

3. Add a condition to the dependent stage using the dynamic variable as shown below

condition: and(succeeded(), eq(dependencies.StageA.outputs['JobA.checkCondition.stageshouldrun'], 'false'))

Following is the full YAML pipeline

pool:
  Azure Pipelines
  
stages:
- stage: StageA
  jobs:
  - job: JobA
    steps:
      - powershell: Write-Host "##vso[task.setvariable variable=dependantstageshouldrun;isOutput=true]true"
        name: checkCondition

- stage: StageB
  condition: and(succeeded(), eq(dependencies.StageA.outputs['JobA.checkCondition.dependantstageshouldrun'], 'true'))
  dependsOn: StageA
  jobs:
  - job: JobB
    steps:
    - powershell:  Write-Host "This is Stage B"

Stage B runs only when the condition in Stage B is true, as shown in the image below.




Change the 'dependantstageshouldrun' variable value to false in Stage A and rerun the pipeline. Then StageB will be skipped because the condition is not fulfilled.







No comments:

Post a Comment