I've tried to find documentation about how in a Jenkinsfile pipeline catching the error that occurs when a user cancels a job in jenkins web UI.
I haven't got the post
or try/catch/finally
approaches to work, they only work when something fails within the build.
This causes resources not to be free'd up when someone cancels a job.
What I have today, is a script within a declarative pipeline, like so:
pipeline {
stage("test") {
steps {
parallell (
unit: {
node("main-builder") {
script {
try { sh "<build stuff>" } catch (ex) { report } finally { cleanup }
}
}
}
)
}
}
}
So, everything within catch(ex)
and finally
blocks is ignored when a job is manually cancelled from the UI.
Abort the job by clicking the red X next to the build progress bar. Click on "Pause/resume" on the build to pause. Click on "Pause/resume" again to resume the build.
The checkout step will checkout code from source control; scm is a special variable which instructs the checkout step to clone the specific revision which triggered this Pipeline run.
The option skipDefaultCheckout is to prevent checking out a repository automatically in the build agent when you haven't explicitly defined a checkout step in one of your stages.
Enable on: freestyle job On a freestyle job, the plugin can be enabled under the Environment section. Among other options, there is also a checkbox for "SCM Skip". After enabling plugin there are also options to override matching regex and enable deletion of skipped build.
Non-declarative approach:
When you abort pipeline script build, exception of type org.jenkinsci.plugins.workflow.steps.FlowInterruptedException
is thrown. Release resources in catch
block and re-throw the exception.
import org.jenkinsci.plugins.workflow.steps.FlowInterruptedException
def releaseResources() {
echo "Releasing resources"
sleep 10
}
node {
try {
echo "Doing steps..."
} catch (FlowInterruptedException interruptEx) {
releaseResources()
throw interruptEx
}
}
Declarative approach (UPDATED 11/2019):
According to Jenkins Declarative Pipeline docs, under post
section:
cleanup
Run the steps in this post condition after every other post condition has been evaluated, regardless of the Pipeline or stage’s status.
So that should be good place to free resources, no matter whether the pipeline was aborted or not.
def releaseResources() {
echo "Releasing resources"
sleep 10
}
pipeline {
agent none
stages {
stage("test") {
steps {
parallel (
unit: {
node("main-builder") {
script {
echo "Doing steps..."
sleep 20
}
}
}
)
}
post {
cleanup {
releaseResources()
}
}
}
}
}
You can add a post trigger "cleanup" to the stage:
post {
cleanup {
script { ... }
sh "remove lock"
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With