Home > Software design >  How to create an object in an Azure pipeline task and return it as a variable to be used in other ta
How to create an object in an Azure pipeline task and return it as a variable to be used in other ta

Time:09-14

I'd like to --for example-- return systeminfo in an object and use it later on.

I checked out this answer but not sure if it works for objects as well: Use an output variable as a global variable in Azure yaml pipeline

Can I specify an empty object as a variable at the beginning of the yaml file, and then set it using powershell?

Thanks.

CodePudding user response:

Your needs are achievable in a sense.

But you can't use typed variables under the concept of pipeline. The reason is clearly describe here:

https://docs.microsoft.com/en-us/azure/devops/pipelines/process/expressions?view=azure-devops#variables

Variables are always strings.

Inside scripts or code in a pipeline, typed variables are possible. But when variables are passed between stages, jobs, and steps under the concept of pipeline, you must still use the form of string.

The below is a sample for using .NET class library to create hash set and store ip addresses in it. The data can be passed in the pipeline, it can also determine if the set is empty.

trigger:
- none

pool:
  vmImage: ubuntu-latest

steps:

- task: PowerShell@2
  name: setOutput
  inputs:
    targetType: 'inline'
    script: |
      #powershell create a hashset to store ips
      
      $set = New-Object System.Collections.Generic.HashSet[String]
      
      $set.Add("1.1.1.1") #complexity is O(1)
      $set.Add("2.2.2.2")
      $set.Add("3.3.3.3")
      
      #for each ip in the set, do something
      
      foreach ($ip in $set)
      {
          #do something
          Write-Host $ip
      }
      
      #save the set to a string
      
      $setString = $set -join " "
      Write-Host $setString
      Write-Host "##vso[task.setvariable variable=myOutputVar;isoutput=true]$setString" #variable in yml is always string.
      

- task: PowerShell@2
  name: getOutput
  inputs:
    targetType: 'inline'
    script: |
      # Write your PowerShell commands here.
      
      Write-Host $(setOutput.myOutputVar)
      $setString = "$(setOutput.myOutputVar)"
      $set2 = New-Object System.Collections.Generic.HashSet[String]
      if($setString -ne "")
      {
          foreach ($ip in $setString.Split(" "))
          {
              Write-Host $ip
              $set2.Add($ip)
          }
      }
      else{
          Write-Host "Null"
      }
  • Related