Thursday, January 14, 2021

Azure Pipelines: Passing Variables Between Jobs and Stages

In this post, let's see how we can pass variables between Stages and Jobs in Azure Pipelines..

Consider the following simple pipeline.

stage: Build
  - job: FirstJob
      vmImage: 'windows-latest'
     - bash: echo "##vso[task.setvariable variable=myVariable;isOutput=true]Hello World"
       name: stepSetVariable
  - job: SecondJob
    dependsOn: FirstJob
      vmImage: 'ubuntu-latest'
      # Map variable
      # syntax: $[ dependencies.{JobName}.outputs['{stepName}.{variableName}'] ]
      myJobVariable: $[ dependencies.FirstJob.outputs['stepSetVariable.myVariable'] ]  
    # Echos Hello World
    - script: echo $(myJobVariable)
      name: stepEchoVariable

stage: Deployment
  dependsOn: Build
    vmImage: 'macOS-latest'
    # Map variable
    # syntax: $[ stageDependencies.{BuildName}.{JobName}.outputs['{stepName}.{variableName}'] ]
    myStageVariable: $[ stageDependencies.Build.FirstJob.outputs['stepSetVariable.myVariable'] ]
  - job: DeploymentJob
    # Echos Hello World
    - script: echo $(myStageVariable)
      name: stepEchoVariable


  • I have 2 Stages, Build and Deployment
  • Build stage has 2 jobs, 
    • In the FirstJob, I am creating a variable called myVariable. I am making it an output variable and setting its value to Hello World.
    • In the SecondJob
      • The SecondJob is depending on FirstJob because the variable needs to be created first. 
      • Then I am declaring a variable called myJobVariable and mapping it with myVariable created in FirstJob. Since it's within the same Stage, I can map the variable using this syntax. 
$[ dependencies.{JobName}.outputs['{stepName}.{variableName}'] ]
      • Then I am just printing the value of myJobVariable
  • In Deployment stage,
    • This stage is depending on Build stage, again because we are trying to access an output variable from Build stage.
    • Then I am declaring a variable called myStageVariable and mapping it with myVariable created in Build stages' FirstJob. Since it's in a different Stage, I can reference the variable using stageDependencies
$[ stageDependencies.{BuildName}.{JobName}.outputs['{stepName}.{variableName}'] ]

    • Then I have just a single job to print the value of myStageVariable

Note: I have used different images for two jobs in Build stage and for the Deployment stage, so the concept is more clear.

Hope this helps.

Happy Coding.


No comments:

Post a Comment