Search code examples
azure-devopsyamlazure-pipelinesmultistage-pipeline

Pass variables from one job to an other in an azure multi stage pipeline (YAML)


I have a very basic YAML azure pipeline

jobs:
- job: Foo
  steps:
  - bash: |
      echo "Create variable xyz"
      echo "##vso[task.setvariable variable=xyz;]yes"
    displayName: 'Determine slot name'
  - bash: |
     echo "Var is: $(xyz)"
    displayName: 'Show variable'
- job: Bar
  dependsOn: Foo
  steps:
  - bash: |
      echo "Hello world $(Foo.xyz)"
    displayName: 'Show variable'

In the first JOB, named Foo, the variable xyz is set to yes. Which works, because I can display it in the seconds step with the line

echo "Var is: $(xyz)"

However, I would like to use that variable in the next job (named Bar). But whatever I do it does not exist. I tried things like

 echo "Hello world $(xyz)"

or

 echo "Hello world $(Foo.xyz)"

But both give the following error when I run the pipeline

 line 1: Foo.xyz: command not found

How can I share that variable between jobs? and sharing between stages would be nice too!!


Solution

  • So you have here actually two things.

    Pass variables from job to job which is possible:

    Did you try multi job output variable:

    jobs:
    
    # Set an output variable from job A
    - job: A
      pool:
        vmImage: 'vs2017-win2016'
      steps:
      - powershell: echo "##vso[task.setvariable variable=myOutputVar;isOutput=true]this is the value"
        name: setvarStep
      - script: echo $(setvarStep.myOutputVar)
        name: echovar
    
    # Map the variable into job B
    - job: B
      dependsOn: A
      pool:
        vmImage: 'ubuntu-16.04'
      variables:
        myVarFromJobA: $[ dependencies.A.outputs['setvarStep.myOutputVar'] ]  # map in the variable
                                                                              # remember, expressions require single quotes
      steps:
      - script: echo $(myVarFromJobA)
        name: echovar
    

    Please check this question.

    Pass variable from stage to stage: which is not possible out of the box at the moment.

    Please check this question. Merlin Liang - MSFT explained this there.

    Workaround

    You can try write down to some file your variables, publish it as pipelineartifact, download this artifact in another stage and load variables. Please check this link.