Azure Devops - Matrix Strategy - Conditional Job Run

Viewed 656

*please ignore formatting issue

trigger:
 - none
parameters:
- name: stg
displayName: "Environment Names"
type: string
 
pool:
  vmImage: ubuntu-latest
stages:
  - stage: stage1
    displayName: 'Stage C1'
    jobs:
    - job: jobabc
      strategy:
        maxParallel: 2
        matrix: 
            env_1:
                EnvironmentX: E1
                Browser: IE
            env_2:
                EnvironmentX: E2
                Browser: Firefox
            env_3:
                EnvironmentX: E3
                Browser: Chrome
    displayName: 'Job 1'
    condition: contains('${{parameters.stg}}', $(EnvironmentX))}}  
    steps: 
    - task: CmdLine@2
      displayName: 'My Task '
      inputs:
        script: 'echo Stage C1 $(Browser)' 

I pass stg parameter as E1E3E4.

In Matrix I have defined EnvironmentX whose value can be E1, E2, or E3.

Below code runs Job 3 times with matrix values defined.

I do NOT want to run all 3 jobs but stg parameter value should decide JOb would run for which matrix values.

Job Condition is NOT working? How to fix this please

1 Answers

You could build the matrix conditionally. Not ideal but that will work:

trigger:
 - none
parameters:
- name: stg
  displayName: Environment Names
  type: string

pool:
  vmImage: ubuntu-latest
stages:
- stage: stage1
  displayName: 'Stage C1'
  jobs:
  - job: jobabc
    strategy:
      maxParallel: 2
      matrix:
        ${{ if contains(parameters.stg, 'E1') }}:
          env_1:
            EnvironmentX: E1
            Browser: IE
        ${{ if contains(parameters.stg, 'E2') }}:
          env_2:
            EnvironmentX: E2
            Browser: Firefox
        ${{ if contains(parameters.stg, 'E3') }}:
          env_3:
            EnvironmentX: E3
            Browser: Chrome
    displayName: 'Job 1'
    steps: 
    - task: CmdLine@2
      displayName: 'My Task '
      inputs:
        script: 'echo Stage C1 $(Browser)'

Related