circlecicircleci-workflows

Run CircleCI job if any job in the workflow fails


In CircleCI, I know it's possible to run a step only if the job that contains it has failed, but can the same thing be done with jobs (without adding an extra failure handling step to every job)?

Specifically, I'm trying to send a slack notification if any job (e.g. checkout) in a workflow fails.


Solution

  • I can't see a simple way to do that; at the job level there's no equivalent to the step-level when: on_fail attribute.

    All I can suggest is to use Dynamic Config. Your "Setup Workflow" would include the main jobs you want to check the outcome of, plus a "waiter" job that:

    1. Monitors the status of the main jobs, and once they have all completed it checks if any of them has a Failed status.
    2. If there's at least one Failed, the "waiter" job sets a parameter to true (for example, { "extra-job": true } that you pass to the continue command of the circleci/continuation orb (via the command's parameters parameter), along with the "continuation" config.yml (which will only include the job that sends a slack notification).

    You can find an example of a "waiter" job in this CircleCI Discuss post. It doesn't include the part where you check for Failed statuses and sets the JSON object that'll be later used as a parameter; you'll need to add that.

    In the "continuation" config:

    1. You'll need to declare a boolean pipeline parameter extra-job with a default value of false

    2. The execution of the one workflow that has the "Slack job" will be conditioned on the extra-job pipeline parameter being true:

      when: << pipeline.parameters.extra-job >>
      

    I hope this helps.