How can I conditionally run a job if another job passes or fails?

Dynamic requires Clauses

The requires clause can be used in your configuration to kick off certain jobs depending on the return status of the previous job.

The supported statuses for this are success, failed and canceled, meaning that you can now trigger other jobs even if the previous ones did not succeed.

An example of this may look like:

workflows:
my-workflow:
jobs:
- build
- test:
requires:
- build
- deploy:
requires:
- build
- test
- notify-build-canceled:
requires:
- build: canceled
- cleanup:
requires:
- deploy:
- failed
- canceled

Details on the requires stanza can be found in our documentation.

Conditional Steps

In CircleCI, you can conditionally run jobs based on the results of preceding jobs by using conditional pipelines. This can be achieved by using when and or statements in your pipeline configuration.
Here is an example of how you can conditionally run a job based on the result of another job:
version: 2.1
orbs:
hello: circleci/hello-build@0.0.14
jobs:
my_job:
docker:
- image: circleci/node
steps:
- checkout
- hello/circleci-env-highlights
- hello/hello-triggerer
- run:
name: 'always run this step'
command: echo "I will always run!"
when: always
workflows:
my_workflow:
jobs:
- my_job
In this example, the always run this step step will always run at the end of the job, regardless of whether it passes or fails.
 
You can also use the when clause together with some logic statements to create a workflow that runs jobs when specific conditions are met. For example, you can set up your pipeline to execute a job only if the first job passes.
 

Tutorial

For more information, you can refer to this tutorial on conditional CircleCI pipeline execution.
Please note that currently, conditional jobs aren’t possible in CircleCI, though that would be a good feature request. However, you can create a conditional step using bash. Here is an example:
- run:
name: Check branch
command: |
if [ "${CIRCLE_BRANCH}" == "master" ]; then
echo "foo"
fi
This script checks if the current branch is master and if so, it echoes foo. If you run into issues and show the failed check, there are folks on the CircleCI forums who may be able to help as well.
 

Additional Resources

Was this article helpful?
0 out of 9 found this helpful

Comments

0 comments

Article is closed for comments.