Search code examples
azure-devopscontinuous-integrationazure-pipelinescicd

Pass powershell variable accross multiple agents in Release pipeline


My release pipeline has two different agents, one azurehosted and one selfhosted.

In the Azure hosted agent, i'm setting my variable.

Later, in the self hosted agent, i need to read to variable's value.

However, it's not working to share variable values accross the two agents... any idea?

Attachments:

  1. Variable declaration enter image description here

  2. Variable reading (NOT WORKING) enter image description here


Solution

  • Basically, we can use the Logging commands with isoutput=true to pass variable between jobs for YAML pipelines. See SetVariable: Initialize or modify the value of a variable and Use output variables from tasks for details.

    Write-Host "##vso[task.setvariable variable=outputSauce;isoutput=true]canned goods"
    

    But for the classic release pipelines, it’s not supported to pass variables across jobs/stages like YAML.

    enter image description here

    In your scenario, across multiple agents means in different jobs. So, it doesn't work.

    However, we can use another way to achieve that:

    1. Set a release variable in your pipeline. enter image description here

    2. Make sure the build service account has the permission to manage the release: enter image description here

    3. Enable the option Allow scripts to access the OAuth token in job agent. enter image description here

    4. Add a PowerShell task to run a script to update the current release variable value if needed by calling REST API Releases - Update. You can reference the following PowerShell script to do that. enter image description here

    5. Then we can use the updated variable in other jobs across agents. enter image description here

    PowerShell script for your reference:

    $url = "$($env:SYSTEM_TEAMFOUNDATIONSERVERURI)$env:SYSTEM_TEAMPROJECTID/_apis/release/releases/$($env:RELEASE_RELEASEID)?api-version=7.0"
    Write-Host "URL: $url"
    $pipeline = Invoke-RestMethod -Uri $url -Headers @{
        Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
    }
    Write-Host "Pipeline = $($pipeline | ConvertTo-Json -Depth 99)"
    
    # Update an existing variable named FOO to its new value 1234
    $pipeline.variables.FOO.value = "1234"
    
    #****************** update the modified object **************************
    $json = @($pipeline) | ConvertTo-Json -Depth 99
    
    
    $updatedef = Invoke-RestMethod -Uri $url -Method Put -Body $json -ContentType "application/json" -Headers @{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"}
    
    write-host "==========================================================" 
    
    Write-host "The value of Varialbe 'FOO' is updated to" $updatedef.variables.FOO.value
    
    write-host "=========================================================="