Monday, May 20, 2024

Share Dynamic Variables Between Azure DevOps Stages

This blog post explains how to generate dynamic variables while running Azure DevOps tasks and how to utilize them in subsequent tasks in dependent stage.

Prerequisites: Azure DevOps account

The following YAML pipeline consist with two stages called GenerateGuid and PrintGUID

1. Two GUIDs are generated within Job1 in GenerateGuid stage and are designated as output variables using the script below. 'demovariable01' is the dynamic variable name.           

    

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

2. The dynamically defined variable can be utilized in the dependent stage by defining a variable following pattern below.

<<variable name>> : $[ stageDependencies.<stage name >.<name of the job>.outputs['<name of the task which generates variables dynamically>.<dynamically generated variable name>']]

Ex:
var01: $[ stageDependencies.GenerateGuid.Job1.outputs['generateGuids.demovariable01'] ]  

The following YAML Script demonstrates how to dynamically generate variables in one stage and utilize those values in a dependent stage.


pool:
  Azure Pipelines

stages:
  - stage: GenerateGuid
    jobs:
    - job: Job1
      steps:

      - task: PowerShell@2
        name: generateGuids
        inputs:
          targetType: 'inline'
          script: |
            $guid1 = [guid]::NewGuid()
            $guid2 = [guid]::NewGuid()
            Write-Host "##vso[task.setvariable variable=demovariable01;isOutput=true]$guid1"
            Write-Host "##vso[task.setvariable variable=demovariable02;isOutput=true]$guid2"

  - stage: PrintGUID
    dependsOn: GenerateGuid
    jobs:
    - job: Job2    
      variables:
        var01: $[ stageDependencies.GenerateGuid.Job1.outputs['generateGuids.demovariable01'] ]  
        var02: $[ stageDependencies.GenerateGuid.Job1.outputs['generateGuids.demovariable02'] ]  
      steps:
      - task: PowerShell@2
        name: Print_demovariable_01
        inputs:
          targetType: 'inline'
          script: |         
            Write-Host $(var01)

      - task: PowerShell@2
        name: Print_demovariable_02
        inputs:
          targetType: 'inline'
          script: |          
            Write-Host $(var02)  

After executing the pipeline, you will be able to see results similar to the image below.



No comments:

Post a Comment