This article describes how to run a step to do cleanup and recovery operations, even if the job is interrupted by a failure or the user aborts it. A variant: You may want to do some cleanup in a failure case only.
A cleanup step is useful when you have a job with many steps. For example, the early steps may create a directory and populate it, the middle steps do the build and testing, and the later steps publish the results and do cleanup. If the first set of steps do not complete, there is no point in running the middle steps, but cleanup may need to be done. The cleanup may be different if the job did not actually complete.
The approach is to use three CloudBees CD (CloudBees Flow) features in combination:
Step error handling to abort a job when a step fails
"Always run" flag on a step to run a cleanup step when a failure occurs
Property stored on a job to communicate across steps
mkdir "BuildDir"; mkdir "BuildDir/tempfiles";
To illustrate error handling and cleanup, this is written as a step that always fails. Error handling is set to abort the procedure in case of an error.
The next steps run the build, tests, and so on. At the end, a step sets a property that shows the procedure completed without being aborted. This property will be used in the cleanup step to determine the type of cleanup to do.
ectool setProperty /myJob/buildCompleted 1
The final step does the cleanup and is marked to "always run."
Always run step:
For added efficiency, the Perl script above can be tweaked to use ElectricCommander.pm and communicate with the server rather than using ectool. See KBEC-00020 for details.