Ramakrishnan Ramar
Ramakrishnan Ramar

Reputation: 27

Azure DevOps YAML Split & Each

We have variable group in Pipeline and it has below input

Input: Instance1,Instance2,Inastance3

Expected Output: Instance1 Instance2 Inastance3

We tried below YAML Code

trigger:
- main

pool:
  vmImage: ubuntu-latest
variables:
- group: "DevInstanceList"
- name: InstancesList
  value: $[variables.Instances]

steps:
- script: echo $(InstancesList) 
- ${{ each env in split(variables.InstancesList, ',')}}:
    - script: echo ${{ env }} 

We tried to split using comma seperator and getting below error.

Error: syntax error: invalid arithmetic operator (error token is ".Instances")

Instance Defined in Library--> Group variable enter image description here Please share your thoughts

Upvotes: 1

Views: 7819

Answers (2)

Dilly B
Dilly B

Reputation: 1462

You could try a powershell task like:

- powershell: |
   
   $results = "$(InstancesList)".Split(" ")
   $result[0]
   $result[1]
   $result[2]
  displayName: 'PowerShell Script to split variables'

Note: A space between double quotes in split function. Updated Answer: I Tested the code it works:

trigger: none

pool:
  vmimage: ubuntu-latest

variables:
 - group: TestVariablegroup

steps:
- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
      # Write your PowerShell commands here.
      echo $(InstancesName)
      $results = "$(InstancesName)".split(",")
      foreach ($instance in $results){
        Write-Host "The selected Instance Name is - $($Instance)"
      }

Adding variablegroup Image FYR: VariableGroup

Adding Results Image FYR: Output Image

Upvotes: 0

Ging Yuan-MSFT
Ging Yuan-MSFT

Reputation: 747

Based on my test, the $[] cannot be fetched in compile time use for each. As @Daniel mentioned. If you are using '$(Instances)' in "each", you will find the empty.

For more information, you can refer to Runtime expression syntax.

So you can try to provide the value in the YAML file.

YAML like:

variables:
- group: "DevInstanceList"
- name: InstancesList
  value: Instance1,Instance2

steps:
- ${{ each env in split(variables.InstancesList, ',')}}:
    - script: echo ${{ env }} 

Upvotes: 4

Related Questions