azure-devopsazure-pipelinesazure-pipelines-yaml

Azure Devops Pipeline conditional expression


How can I use loops in condition expression for a task?

I have a stage in pipeline that depends on other stages in the same pipeline. Stage names are dynamically generated. How can I add a condition that checks if any one of the stage has executed successfully?

For e.g.,

parameters:
- name: modules
  default:
    - name: module1
      type: typeA
    - name: module2
      type: typeB

stages:
- ${{ each module in parameters.modules}}:
  - stage: ${{module.name}}
    jobs:
    - job: build${{module.name}}

- stage: result
  dependsOn:
  - ${{ each module in parameters.modules}}:
    - ${{module.name}}
  condition: and(not(failed()), or any of the dependent jobs succeeded)
  jobs:
  - job: deployStage

I tried accessing the status of the stage/task in powershell inline script, but that also does not return any results: "dependencies.$stagename.$jobname.outputs"


Solution

  • Consider adding a condition property to the parameter elements and use filtered arrays to dynamically set the dependencies and conditions of the final stage.

    Working example:

    trigger: none
    
    parameters:
      - name: modules
        type: object
        default:
          - name: module1
            type: typeA
            condition: "eq(dependencies.module1.result, 'Succeeded')"
            # condition: in(dependencies.module1.result, 'Succeeded', 'SucceededWithIssues')
            exitCode: 0 # For testing purposes only: 0 for success, other for failure
          - name: module2
            type: typeB
            condition: "eq(dependencies.module2.result, 'Succeeded')"
            # condition: in(dependencies.module2.result, 'Succeeded', 'SucceededWithIssues')
            exitCode: 0 # For testing purposes only: 0 for success, other for failure
    
    stages:
      - ${{ each module in parameters.modules }}:
        - stage: ${{ module.name }}
          displayName: ${{ module.name }}
          dependsOn: []
          jobs:
            - job: build${{ module.name }}
              displayName: ${{ module.name }}
              steps:
                - checkout: none
                - script: |
                    exit ${{ module.exitCode }}
                  displayName: 'Run ${{ module.name }} - ${{ module.type }}'
    
      - stage: result
        displayName: 'Result'
        dependsOn: ${{ parameters.modules.*.name }}
        condition: or(${{ join(',', parameters.modules.*.condition) }})
        jobs:
          - job: deploy
            displayName: 'Deploy'
            steps:
              - checkout: none
              - script: |
                  echo "Conditon: or(${{ join(',', parameters.modules.*.condition) }})"
                displayName: 'Print condition'
    

    Expression or(${{ join(',', parameters.modules.*.condition) }}) will generate the following string: