variablesazure-devopsyamlazure-pipelinesazure-pipelines-yaml

Azure DevOps YAML: How to convert an array into formatted string?


In my Azure DevOps YAML pipeline, I have a parameter defined as an array:

parameters:
  - name: variablesToSubstitute
    type: object
    default:
      - test1
      - test2

I need to convert this array into a multiline string where each element follows the format key=$(key). The desired result should look like this:

variables:
  result: |
    test1=$(test1)
    test2=$(test2)

or this:

variables:
  result: test1=$(test1) test2=$(test2)

How can I achieve this in Azure DevOps YML? Is there a way to loop through the array and format each element into this structure?


Solution

  • You can use the join syntax to merge your array with a line break.

    variables:
      result: ${{ join('\n', parameters.variablesToSubstitute) }}
    
    steps:
    - script: printf "$(result)"
    

    enter image description here

    To apply a format to each item, there's a limitation with ${{ each }} in that it cannot appear inside an expression that is a scalar value. Best I can do is pass the formatted values into a template and then join them.

    # template: concatenate-variables
    parameters:
    - name: items
      type: object
    
    - name: variable
      type: string
    
    variables:
    - name: ${{ parameters.variableName }}
      value: ${{ join('\n', parameters.items }}
    
    # pipeline
    parameters:
    - name: variablesToSubstitute
      type: object
      default:
      - test1
      - test2
    
    variables:
    - template: concatenate-variables.yml
      parameters:
        items:
        - ${{ each item in parameters.variablesToSubstitute }}:
          - ${{ format('{0}=$({0})', item) }}
        name: result
    
    steps:
    - script: printf "$(result)"
    

    enter image description here