Loop through dynamic template parameters in Azure devops YAML

Viewed 5731

I want to perform some actions (publish) on an array of string which are passed as parameter. The thing is, this parameter is dynamic :

# pipeline.yml

- job: MyJob
    pool:
      [...]
    steps:
      - pwsh: |
          $affected = ['app-one', 'app-two'] # Here I hardcoded the array but in my real code this is set dynamically
          Write-Host "##vso[task.setvariable variable=affected;isOutput=true]$affected"
        name: setAffected
        displayName: 'Settings affected'

- template: ./build.yml
  parameters:
    affected: $[ dependencies.Affected.outputs['setAffected.affected'] ] # Here I pass the array of string to the template
# build.yml

parameters:
  affected: ''

jobs:
  - job: Build
    condition: succeeded('Affected')
    dependsOn: Affected
    pool:
      [...]
    variables:
      affected: ${{ parameters.affected }}
    steps:
      - ${{each app in $(affected)}}:
          - pwsh: |
              Write-Host "${{app}}"
      - ${{each app in parameters.affected}}:
          - pwsh: |
              Write-Host "${{app}}"

Neither of ${{each app in $(affected)}} or ${{each app in parameters.affected}} work... How can I manage to execute some actions on each of my array item?

Thanks

1 Answers

Within a template expression, you have access to the parameters context that contains the values of parameters passed in. Additionally, you have access to the variables context that contains all the variables specified in the YAML file plus the system variables. Importantly, it doesn't have runtime variables such as those stored on the pipeline or given when you start a run. Template expansion happens very early in the run, so those variables aren't available.

https://docs.microsoft.com/en-us/azure/devops/pipelines/process/templates?view=azure-devops

Related