Posted in:

I have recently been working with Azure Pipelines and found myself needing to pass a variable between "steps".

In theory, this should have been simple, but unfortunately, a lot of the documentation I followed assumed that you were passing a variable between "jobs", which requires setting isOutput=true, and this didn't work for what I was trying to do.

If you're new to Azure Pipelines, this diagram shows the relationship between "stages", "jobs" and "steps":

Stages Jobs Steps

After a bit of trial and error I got something that works. In this example, my pipeline has two "steps". The first is a PowerShell task that uses task.setvariable to set a variable called message to a string I'd previously set up.

steps:
- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
        $myMessage="Hello World"
        echo "##vso[task.setvariable variable=message]$myMessage";
  displayName: 'Set variable'

And then the second step, we can use the $(message) syntax, or access it as an environment variable with $env:message. (By the way, I also tried passing a variable from one step to the next by setting an environment variable, but that didn't seem to work).

- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
        echo "Message variable is $(message)."
        echo "Message env variable is $env:message."
  displayName: 'Read variable'

Hope that's helpful to someone.