Unfortunately, CircleCI 2.0 workflow doesn't support cancellation of redundant builds as opposed to 1.0 version. When you push your code too often, the whole CI workflow can be stuck unless all your previous jobs are performed.
- The script inside docker container understands repository, current branch and build number from built-in ENV variables
- Fetches the list of the running or enqueued builds within current branch
- Excludes current build from the list of candidates
- Cancels redundant builds one by one
Ready docker image is available on Docker Hub.
- Generate CircleCI API using your account dashboard
- Add it as
CIRCLE_TOKENenvironment variable to your project settings - Add a separate job using
sponomarev/circleci-cancel-buildsdocker image as a required first step in your build workflow - Invoke
runcommand
version: 2
workflows:
version: 2
build_and_test:
jobs:
- cancel_redundant_builds
- checkout:
requires:
- cancel_redundant_builds
jobs:
cancel_redundant_builds:
docker:
- image: sponomarev/circleci-cancel-builds
steps:
- run:
name: Cancelling redundant builds
command: runHonestly, this solution is not ideal – it requires your workflow to start and cancellation job to be invoked. It can take some time before you get a released container, but still, it's better than nothing. It's a pity that CircleCI API doesn't provide any way to control workflows directly.
A big thanks to Luberj from CircleCI forum who provided an idea to cancel builds with API methods.
The code is available as open source under the terms of the MIT License.