StuartvdLee
StuartvdLee

Reputation: 97

Pass variable between Azure Pipelines deployment jobs

We have two deployment jobs that run in the same stage. The first job creates an output variable and the second job uses that output variable (code borrowed from here and implemented the same way in our pipeline).

jobs:
- deployment: producer
  environment:
    name: ${{ parameters.environment }}
    resourceType: VirtualMachine
    tags: ${{ parameters.tags }}
  strategy:
    runOnce:
      deploy:
        steps:
          - script: echo "##vso[task.setvariable variable=myOutputVar;isOutput=true]this is the deployment variable value"
            name: setvarStep
          - script: echo $(setvarStep.myOutputVar)
            name: echovar

- deployment: consumer_deploy
  dependsOn: producer
  variables:
    myVarFromDeploymentJob: $[ dependencies.producer.outputs['deploy_Vm1.setvarStep.myOutputVar'] ]
  environment: 
    name: ${{ parameters.environment }}
    resourceType: VirtualMachine
    tags: ${{ parameters.tags }}
  strategy:
    runOnce:
      deploy:
        steps:
          - script: "echo $(myVarFromDeploymentJob)"
            name: echovar

This works because we reference the virtual machine (hardcoded) that the producer deployment job runs on. However, not every stage will run on the same virtual machine.

I've tried regular variables ($(Agent.MachineName)), as well as expression syntax, passing the variable from a template file and changing the scope of the variable template, but none of them work and the 'myVarFromDeploymentJob' variable stays empty.

Is there a way to make the virtual machine name in the expression variable or more flexible? So going from this:

$[ dependencies.producer.outputs['deploy_Vm1.setvarStep.myOutputVar'] ]

To something like this:

$[ dependencies.producer.outputs['deploy_$(Agent.MachineName).setvarStep.myOutputVar'] ]

Upvotes: 3

Views: 3880

Answers (1)

michal.mlaka
michal.mlaka

Reputation: 11

Adding a solution for others.

here missing link to docs: https://learn.microsoft.com/en-us/azure/devops/pipelines/process/deployment-jobs?view=azure-devops#support-for-output-variables

for runOnce deployment depends if you are addressing whole deployment (repeat Job name) or resource deployment (use deploy_resourceName):

variables:
  myVarFromDeploymentJob: $[ dependencies.A2.outputs['A2.setvarStepTwo.myOutputVar'] ]
  myOutputVarTwo: $[ dependencies.A2.outputs['Deploy_vmsfortesting.setvarStepTwo.myOutputVarTwo'] ]

Upvotes: 1

Related Questions