In our previous post, we already discussed about “How to pass values between Tasks in a Pipeline” where we can pass single value from one task/job/stage to another in pipeline. But incase, if you want to share the object from one task/job/stage to another instead of single value then we need to perform some trick to achieve this. In this quick post we will discuss about trick that I have found recently to store an object in an Azure Pipelines variable from a PowerShell script (How to pass objects between tasks in Azure pipeline).
The problem
Setting a variable in a script for later use in an Azure DevOps’ pipeline is possible using the task.setvariable command as described in below post.
This works great for simple variables like below:
1 2 3 4 5 6 7 |
steps: - pwsh: | Write-Host "##vso[task.setvariable variable=variableName]variableValue" - pwsh: | Write-Host "Value from previous step: $(variableName)" |
But it is bit trickier for sharing the complex variables likes objects, arrays, or arrays of objects between taks/stage/jobs in pipeline.
The solution
As an example, let’s we try to retrieve the name, type and resource group of all the resources in an Azure subscription as shown in the below script. Let we see how can pass this value of $resources in pipeline.
1 2 3 |
$azure_resources = Get-AzResource | Select-Object -Property Name,Type,ResourceGroupName |
First you can store an object in an Azure Pipelines variable using the PowerShell task. Next, you can simply serialize it in JSON and apply in single input like below: -Compress flag which conver JSON to a single line.
1 2 3 |
$azure_resourcesJson = $azure_resources | ConvertTo-Json -Compress |
Pass objects between tasks in Azure pipeline
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
pool: name: devopsagent-win-pprd steps: - task: AzurePowerShell@5 inputs: azureSubscription: 'Azure_Digital' azurePowerShellVersion: LatestVersion ScriptType: InlineScript Inline: | $azure_resources = Get-AzResource | Select-Object -Property Name,Type,ResourceGroupName -First 3 $azure_resourcesJson = $azure_resources | ConvertTo-Json -Compress Write-Host "##vso[task.setvariable variable=resources]$azure_resourcesJson" - pwsh: | $resources = '$(resources)' | ConvertFrom-Json Write-Host "There are $($resources.Count) resources in the list" Write-Host "There are resources are" $resources.ResourceGroupName |
Leave A Comment