Saturday, February 3, 2024

Share Dynamic Variables Between Azure DevOps Jobs

Azure DevOps pipelines can be defined with multiple jobs based on the final result to be achieved and specific requirements. There may arise situations where variable values need to be dynamically generated within one pipeline job and utilized in another subsequent job. This blog explains the process of achieving such functionality.

Prerequisites: Azure DevOps account

The following pipeline consist of two jobs named Job1 and Job2. 

1. Two GUIDs are generated within Job1 and are designated as output variables using the script below.

    Write-Host "##vso[task.setvariable variable=<<output variable name>>;isOutput=true]<<guidvalue>>

2. With in Job 2, variables are defined as follows.

    <<Variablename>> : $[dependencies.<<parentjobname>>.outputs['<<name of  task generate with output values>>.<<output variable name>>']]

The following pipeline demonstrates how to generate two GUIDs, set them as output variables in job 1, and subsequently utilize them in Job 2.

trigger:
  branches:
    include:
      - 'main'
pool:
  Azure Pipelines

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"

  
  - job: Job2
    dependsOn: Job1
    variables:
      var01: $[ dependencies.Job1.outputs['generateGuids.demovariable01'] ]  
      var02: $[ dependencies.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 observe the values generated from Job1 printed in Job 2, as shown below.





No comments:

Post a Comment