Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through variables in Azure pipeline

I have a text file with two names in it client1 and client2.

I have a Powershell script made to read the text file and my understanding of it is that it creates an array already.

$clientvariable = Get-Content -Path {FilePath}/{File};
Write-Host "vso[task.setvariable variable=clientname]$clientvariable

So now clientname has the value $clientvariable which is set to client1 client2 and I can index each position if needed.

How can I use this in an Azure pipeline YAML so that each name can be individually looked at and looped through one after the next?

The goal is to take each name and create a resource with the name from the file in conjuction with an ARM template i.e. client1SQLserver client2SQLserver

I've seen that you can use templates with parameteres to create for loops so would that work in this case or is there some other way to do what I'm looking for?

like image 450
rk92 Avatar asked Oct 14 '25 19:10

rk92


1 Answers

How can I use this in an Azure pipeline YAML so that each name can be individually looked at and looped through one after the next?

We could specify that a job run based on the value of an output variable set in a previous job to loop each name individually.

Since I do not have text file name, I use the custom character array instead of file names in my sample, like $FileNames = '"test1","test2","test3","test4"':

My Azure pipeline yaml file:

trigger:
    branches:
      include:
        - master


    stages:
      - stage: LoopFileName
        jobs:
        - job: A
          pool:
            name: MyPrivateAgent
          steps:
          - task: PowerShell@2
            condition: succeeded()
            displayName: "Create a list"
            inputs:
              targetType: 'inline'
              script: |
                  $FileNames = '"test1","test2","test3","test4"'
                      Write-Host "##vso[task.setvariable variable=LoopFileName;isOutput=true]$FileNames"                
            name: fileoutput
    
        - job: B
          dependsOn: A
          pool:
            name: MyPrivateAgent
          variables: 
            AllFileNames: $[dependencies.A.outputs['fileoutput.LoopFileName']]
          steps:
          - template: loopTemplate.yml
            parameters: 
              files : $(AllFileNames)

Then the loopTemplate.yml file:

parameters:
  files: []

steps :
- task: PowerShell@2
  displayName: 'Fetching ValueFiles'
  inputs:
    targetType: 'inline'
    script: >

      foreach ($i in ${{parameters.files}})
      {
        Write-Host "filenames=$i"
      }

The test result:

enter image description here

In this case, we could create a resource with the name.

You could check the document Conditions for some more details.

like image 158
Leo Liu-MSFT Avatar answered Oct 17 '25 08:10

Leo Liu-MSFT