DevOps | Scripts | Automation

Azure DevOps

How to pass variable between Stages in Azure Pipeline?

In the previous article, we have seen how we can pass variable values between two tasks. If you have missed reading, the link is below.

https://theautomationcode.com/how-to-pass-variables-between-tasks-in-azure-pipeline/

This article will discuss how we can pass variables between the pipeline stages.

Scenario:

Consider the below scenario, where we need to pass the VMName variable value of task-1 in stage-1 to the tasks the stage-2

This passing variable between stages isn’t like passing it between tasks in the same stage but storing variable value will remain the same as we have seen in the previous article except we have to add one more keyword to pass value is “isOutput=true“. See the example below.

Write-Host “##vso[task.setvariable variable=vmList;isOutput=true]$VMs”

Here, we are storing $VMs variable output to the $(vmList) variable of the pipeline.

Once the variable is generated and stored in the task, we need to follow a specific format to pass between stages as shown below.

stageDependencies.StageName.JobName.outputs[‘taskName.variableName’]

Look at the code now, for stage 1.

trigger:
- none

pool:
  vmImage: windows-latest

stages:
  - stage: Stage1
    jobs:
      - job: Job1
        steps:
          - task: PowerShell@2
            name: Task1
            displayName: Create and Store variable
            inputs:
              targetType: 'inline'
              script: |
                $VMs = @("TestVM1","TestVM2","TestVM3")
                Write-Host "##vso[task.setvariable variable=vmList;isOutput=true]$VMs"

          
          - task: PowerShell@2
            name: Task2
            displayName: Some Random task
            inputs:
              targetType: 'inline'
              script: |
                Write-Host "Running random task"
  

In the above code, we have generated the $VMs variable in task1 of stage1. In Stage2, we can use the variables section of Job1 to ensure that the $VMs variable can be used by all jobs in Stage2.

Below is the code for stage2.

  - stage: Stage2
    jobs:
      - job: Job1
        variables: 
           vmList: $[ stageDependencies.Stage1.Job1.outputs['Task1.vmList'] ]
        steps:
          - task: PowerShell@2
            name: Task1
            displayName: Get Variable From Stage1
            inputs:
              targetType: 'inline'
              script: |
                Write-Host "VM List: $(vmList)"

We are getting vmList variable output in the variables section of Job1 and the same has been displayed in the output using $(vmList).

Stages are completed
Output of the variable from Stage1

The purpose of using the variables section in Stage-2 is so that the other tasks can also utilize the vmList variable.

The entire pipeline code you can find on GitHub.

https://github.com/chiragce17/MyPublicRepo/blob/main/AzurePipeline/PassVariablesBetweenStages.yml