Romeo Mihalcea
Romeo Mihalcea

Reputation: 10242

Azure Pipelines overwrite pipeline variable

How does one overwrite a pipeline variable or how does one create a pipeline variable from a job?

I'm running a prepare job where I extract the current git tag into a variable that I need in following jobs so I decided to create a pipeline variable and overwrite its value in the first job:

variables:
  GIT_TAG: v0.0.1

jobs:
- job: job1
  pool:
    vmImage: 'ubuntu-16.04'
  steps:
    - powershell: |
        Write-Host "##vso[task.setvariable variable=GIT_TAG]$(git describe --tags --always)"

But, in the next job GIT_TAG has the initial value of v0.0.1.

Upvotes: 4

Views: 12832

Answers (1)

Shayki Abramczyk
Shayki Abramczyk

Reputation: 41545

By default, if you overwrite a variable the value is available only to his job, not to the sequence jobs.

Passing variables between jobs in the same stage is a bit more complex, as it requires working with output variables.

Similarly to the example above, to pass the FOO variable:

  1. Make sure you give a name to the job, for example job: firstjob
  2. Likewise, make sure you give a name to the step as well, for example: name: mystep
  3. Set the variable with the same command as before, but adding ;isOutput=true, like: echo "##vso[task.setvariable variable=FOO;isOutput=true]some value"
  4. In the second job, define a variable at the job level, giving it the value $[ dependencies.firstjob.outputs['mystep.FOO'] ] (remember to use single quotes for expressions)

A full example:

jobs:

  - job: firstjob
    pool:
      vmImage: 'Ubuntu-16.04'
    steps:

      # Sets FOO to "some value", then mark it as output variable
      - bash: |
          FOO="some value"
          echo "##vso[task.setvariable variable=FOO;isOutput=true]$FOO"
        name: mystep

      # Show output variable in the same job
      - bash: |
          echo "$(mystep.FOO)"

  - job: secondjob
    # Need to explicitly mark the dependency
    dependsOn: firstjob
    variables:
      # Define the variable FOO from the previous job
      # Note the use of single quotes!
      FOO: $[ dependencies.firstjob.outputs['mystep.FOO'] ]
    pool:
      vmImage: 'Ubuntu-16.04'
    steps:

      # The variable is now available for expansion within the job
      - bash: |
          echo "$(FOO)"

      # To send the variable to the script as environmental variable, it needs to be set in the env dictionary
      - bash: |
          echo "$FOO"
        env:
          FOO: $(FOO)

More info you can find here.

Upvotes: 10

Related Questions