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

Conditional Pipelines

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:
slack: circleci/slack@3.4.2
hello: circleci/hello-build@0.0.14
jobs:
my_job:
docker:
- image: circleci/node
steps:
- checkout
- hello/circleci-env-highlights
- hello/hello-triggerer
- slack/notify:
webhook: '${SLACK_WEBHOOK}'
workflows:
my_workflow:
jobs:
- my_job
In this example, the slack/notify 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.
 
For more advanced concepts, you can hold a workflow and use when and or statements. This allows you to have first-hand experience with the failure of one job causing a cascading failure that shuts down the entire pipeline.
 

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 6 found this helpful

Comments

0 comments

Article is closed for comments.