How to Run a Job Only When a Previous Job Succeeds or Fails in CircleCI
CircleCI runs a job after another succeeds via requires:; for always-run cleanup, use a step when: always.
A job that requires: another only starts when the dependency succeeds. To run a step on failure (alerting) or always (cleanup), use the step-level when: condition inside the job.
Ordering and always-run steps
Deploy requires a successful test; the notify step inside test runs regardless of the test result.
.circleci/config.yml
version: 2.1
jobs:
test:
docker: [{ image: cimg/node:20.11 }]
steps:
- checkout
- run: npm ci && npm test
- run:
name: Always upload logs
command: ./upload-logs.sh
when: always
- run:
name: Alert on failure
command: ./alert.sh
when: on_fail
workflows:
ci:
jobs:
- test
- deploy:
requires: [test]Gotchas
requires:runs a downstream job only on success of its dependency - there is no native "run job on upstream failure" at the workflow level.- Use step-level
when: on_fail/when: alwaysinside the failing job for alerting and cleanup. - A
when: on_failstep still runs even after an earlier step failed - that is the point; keep it idempotent.
Related guides
How to Run Steps on Success or Failure in a Jenkins PipelineRun steps conditionally on outcome in a Jenkins pipeline with the post section - success, failure, unstable,…
How to Pass Data Between Jobs in CircleCIPass data between CircleCI jobs - files via persist_to_workspace/attach_workspace and computed values via a w…