Search code examples
templatesazure-devopsazure-pipelinesexpression

How to run a template job only if the previous job failed in Azure DevOps?


It sounds like a very simple thing, but I've been digging around the internet for hours and can't find a working example.

I would like to have something like:

  - job: A
    displayName: jobA
- ${{ if eq(failed(), true) }}:
  - template: ./template.yaml
    parameters: ...

but it doesn't work. I've tried using an expression, using a condition and also using a job B that's in between just to pass a flag to the expression - still didn't work.

Any suggestions will be greatly appreciated.


Solution

  • The Job status check functions seems is not available for the if, elseif, and else clauses. They are available for the condition key of each stage, each job and each task in the pipeline.

    In addition, to let the template job can get the final status of jobA, the template job should run after jobA. So, you need to set the template job to depends on jobA using the dependsOn key on the template job.

    Then in the template job, you can use the expression "dependencies.A.result" to get the status of jobA. This expression also is not available for the if, elseif, and else clauses.

    Below is an example as reference.

    # template.yaml
    
    parameters:
    - name: dependsOnJob
      type: string
    
    - name: jobCondition
      type: string
    
    jobs:
    - job: TB
      displayName: jobTemplate
      dependsOn: ${{ parameters.dependsOnJob }}
      condition: ${{ parameters.jobCondition }}
      steps:
      . . .
    
    # azure-pipelines.yml
    
    stages:
    - stage: S1
      jobs:
      - job: A
        displayName: jobA
        steps:
        . . .
      
      - template: template.yaml
        parameters:
          dependsOnJob: A
          jobCondition: eq(dependencies.A.result, 'failed')
    

    enter image description here