Thursday, September 12, 2024

Azure Pipelines: Passing Variables Between Jobs

In this post let's see how we can pass variables between jobs in Azure Pipelines.

Let's say we need to pass a variable from JobA to future jobs.

trigger:
main/*

pool:
  vmImage: ubuntu-latest

stages:
stage: StageA
  displayName: Stage A
  jobs:  
  - job: JobA
    displayName: Job A
    steps:
    # Create output variable and set value
    - script: |
        echo "##vso[task.setvariable variable=jobAVariable;isOutput=true]someValue"
      name: outputVariable
      displayName: Output Variable

  - job: JobB
    displayName: Job B
    dependsOn: JobA
    variables:
      # Map the output variable from Job A into Job B
      jobBVariable: $[ dependencies.JobA.outputs['outputVariable.jobAVariable'] ]
    steps:
    # This will print the updated value of the variable
    - script: |
        echo $(jobBVariable)
      name: printUpdatedVariable
      displayName: Print Updated Variable

  - job: JobC
    displayName: Job C
    dependsOn: JobA
    variables:
      # Map the output variable from Job A into Job C
      jobCVariable: $[ dependencies.JobA.outputs['outputVariable.jobAVariable'] ]
    steps:
    # This will print the updated value of the variable
    - script: |
       echo $(jobCVariable)     
      name: printUpdatedVariable
      displayName: Print Updated Variable

Note how StageA.JobA.outputVariable is outputting the variable using isOutput=true. By default jobs run in parallel. So first we need to wait till JobA  completes using dependsOn. Then we can map the variable into any job through dependencies.

Hope this helps.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment