How to pass a list of string parameters to an Azure DevOps template

Viewed 6210

In a previous SO question, I was trying to get create an Azure DevOps template.

Now that I know how to do that, I'm trying to pass in a list of strings to the template and use them in the template, like so:

azure_pipelines.yml

extends:
  template: AzurePipelines/job.yml
  parameters:
    projects:
      - FirstProject.csproj
      - SecondProject.csproj

and in this template...

job.yml

steps:
 (for each projectFileName in projects)
 - bash echo $(projectFileName)
 - run code in the build.yml template using $(projectFileName)
 - run code in the test.yml template using $(projectFileName)
 - run code in the publish.yml template using $(projectFileName)

So for each project name handed into the template, run the template steps.

I'm not sure how to pass in an array of strings and how to test that it works?

2 Answers

It seems you are looking for each function:

# my-template.yml
parameters:
- name: 'projects'
  type: projectList
  default: []
steps:
- ${{ each project in parameters.projects }}:
  - task: PublishBuildArtifacts@1
    displayName: 'Publish ${{ project }}'
    inputs:
      PathtoPublish: '$(Build.ArtifactStagingDirectory)/${{ project }}.zip'
# ci.yml
steps:
- template: my-template.yml
  parameters:
    projects:
    - test1
    - test2

The easiest way I found to accomplish the use of templates is by using the templates from within the main yaml file pipeline. This way you will have access to all the variables and variable groups defined in the main template. Using this architecture you will be able to bundle several steps into a template then run it from the main yaml file. Eg:

azure_pipelines.yml

variables:
- name: projectFileName
  value: "Variable 1 value"
- name: VAR2
  value: "Variable 2 value"

trigger:
  - master

pool:
  vmImage: 'ubuntu-latest'

steps:
- template: templates/job.yml
- template: templates/test.yml

templates/job.yml

steps:
- task: Bash@3
  displayName: 'Run Bash Command'
  inputs:
    targetType: 'inline'
    script: |
      print "Variable value: " $(projectFileName)

Hope it helps

Related