Search code examples
arraysazure-devopsimportyamlazure-pipelines

How to pass array from one file to yaml file


Lets say I have this array:

[ 'value1','value2','value3' ]

I want to pass into my yaml file this array from another file.

my yaml should accept array in this field:

parameters: 
  arrayExpected: arrayValueFromAnotherFile

I could have simply this:

parameters:  
  arrayExpected: [ 'value1','value2','value3' ]

But for specific reasons this is not good approach in my situation. As yaml file cant get very overpopulated with array values.

So far I know that yaml has no imports statements available, perhaps anyone had similar issue and resolved it ?


Solution

  • I want to pass into my yaml file this array from another file.

    You can use another pipeline to get the array from the file, then transfer the parameter value to target pipeline via rest api Runs - Run Pipeline with templateParameters to set the parameters.

    For example, array in array.txt:

    enter image description here

    The 1st pipeline sample, please change the target pipeline definition id to yours.

    trigger: none
    
    pool:
      vmImage: Windows-latest
    
    steps:
    - task: PowerShell@2
      inputs:
        targetType: 'inline'
        script: |
          $array = Get-Content array.txt
          $array = $array.TrimStart("[").TrimEnd("]") 
          Write-Output $array        # check the string content
          $body = @"
          { 
                  "definition": {
                      "id": 565              # your target pipeline definition id
                  },
                  "templateParameters": {
                    "arrayExpected": "$array"
                 }
          }
          "@
          $Uri = "$(System.CollectionUri)$(System.TeamProject)/_apis/build/builds?api-version=7.1-preview.7"
          Write-Host $Uri
          $buildresponse = Invoke-RestMethod -Method Post -ContentType "application/json" -Uri $Uri -Body $body -Headers @{Authorization = "Bearer $(System.AccessToken)"}
          write-host $buildresponse
    

    The target pipeline sample:

    trigger: none
    
    parameters:  
    - name: arrayExpected
      type: string
      default: ""
    
    pool:
      vmImage: ubuntu-latest
    
    steps:
    - script: echo ${{ parameters.arrayExpected }}
    
    - ${{ each value in split(parameters.arrayExpected, ',')}}:
      - script: echo ${{ value }}
        displayName: 'check value'
    

    enter image description here

    I used $(system.accesstoken) to trigger the target pipeline, please make sure build service account has permission on the target pipeline.

    enter image description here