Azure Devops pipeline yml looping over stages

Viewed 1729

How can i loop over an array or through an object to create stages?

Below is a yml file that works. You can see the build stage loops over the parameters environments for jobs. IS it possible to achieve the same thing for the publishing stages?

The publishing stages require manual approval, must run in order and only when the previous stage is successfully complete?

parameters:
  - name: 'environments'
    type: object
    default: 
      - environment: development
        variableGroup: strata2-admin-spa-vg
        dependsOn: 'build'
      - environment: test
        variableGroup: strata2-test-admin-spa-vg
        dependsOn: 'development'
      - environment: production
        variableGroup: strata2-development-variables
        dependsOn: 'development'
  - name: 'buildTemplate'
    type: string
    default: buildTemplate.yml
  - name: 'publishTemplate'
    type: string
    default: publishTemplate.yml

trigger:
  - main

pool:
  vmImage: ubuntu-latest

stages:
  
  - stage: build
    displayName: Build stage
    jobs: 


# Can I do this for stages?
      - ${{each build in parameters.environments}}:
        - template: ${{parameters.buildTemplate}}
          parameters:
            environment: ${{build.environment}}
            variableGroup: ${{build.variableGroup}}


# How to loop over parameters.environments to dynamically create stages
  - stage: Publish_Development
    displayName: Publish development environment
    dependsOn: build
    jobs:
      - template: ${{parameters.publishTemplate}}
        parameters:
          environment: Development_websites
          variableGroup: strata2-admin-spa-vg

  - stage: Publish_Test
    displayName: Publish test environment
    dependsOn: Publish_Dev
    jobs:
      - template: ${{parameters.publishTemplate}}
        parameters:
          environment: Test_websites
          variableGroup: strata2-test-admin-spa-vg

  - stage: Publish_Production
    displayName: Publish production environment
    dependsOn: Publish_Test
    jobs:
      - template: ${{parameters.publishTemplate}}
        parameters:
          environment: Production_websites
          variableGroup: strata2-development-variables
1 Answers

You can create a stages object the same way you created the environments object.

stages: 
  Publish_Development:
   - stage: Publish_Development
   - displayName: Publish development environment
   - dependsOn: 
   - ... 
  Publish_Test
   - stage: Publish_Development
   - ...

Then you can loop over the stages object like you did with environments.

- ${{each stage in parameters.stages}}:
  - stage: ${{ stage.stage }} 
    displayName: ${{ stage.displayName}} 
    dependsOn: ${{ stage.dependsOn}} 
    ...
Related