Run a job when build is cancelled
Description
Often Gitlab CI pipelines will leave various garbage when cancelled. Things like unstopped docker containers, orphaned build files etc. With Gitlabs new auto-cancelling of redundant pipelines, this issue became more pronounced. Also, project users often manually cancel jobs without manually running cleanup jobs.
Proposal
Add when: on-cancel
or similar feature to .gitlab-ci.yml. Could be implemented as a standard Job.
[...]
cleanup:
stage: cleanup
script:
- docker-compose down -v
- rm -rf tmp/
when: on_cancel
This would be more in line with how other when:
clauses work, but would be limited to a single, catch-all cleanup job
Alternatively, this could be implemented on a per-job basis, similar to Environments on_stop feature
compile:
stage: build
script:
- compile stuff
on_cancel: clean-compile-job
clean-compile-job:
stage: cleanup
script:
- rm -rf tmp/*
Links / references
https://gitlab.com/gitlab-org/gitlab-ce/issues/8998
https://docs.gitlab.com/ee/ci/yaml/README.html#when
Documentation blurb
Overview
The feature would make auto-cancelling more complete, allowing for less maintenance around gitlab-runner environments.
Use cases
Developer pushes a quick follow-up commit to the repository, triggering cancellation of the previous, still running build. The cancelled build runs a job cleaning up any leftovers from the unfinished build.