Search code examples
githubgithub-actions

How to run a github actions job on workflow failure?


I want to run a notification job that lets me know that my workflow failed, is there a way to do that without having to needs every job and checking the status of each one?

This is how I would have to do it now but it gets cumbersome if I have a ton of jobs:

jobs:
  first-job:
    runs-on: ubuntu-20.04
    steps:
      - exit 0


  second-job:
    runs-on: ubuntu-20.04
    steps:
      - exit 1

  notify-job:
    runs-on: ubuntu-20.04
    needs: [first-job, second-job]
    if: ${{ always() && (needs.first-job.result == 'failure' || needs.second-job.result == 'failure') }}
    steps:
      - ./notify.sh

I want to simply check if the workflow failed in any capacity at the end, i.e. if any job failed, is that possible?

I see this documentation to check if the triggering workflow failed (https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#running-a-workflow-based-on-the-conclusion-of-another-workflow).

Is there a way to run a finally or ensure status check at the end of the current workflow?


Solution

  • I found this less verbose syntax:

    if: ${{ always() && contains(needs.*.result, 'failure') }}
    

    Meaning, if any of the jobs listed in needs return "failure" then run this job...

    Source: https://docs.github.com/en/actions/learn-github-actions/expressions#contains