问题
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 postor 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.
回答1:
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..."
sleep 20
} catch (FlowInterruptedException interruptEx) {
releaseResources()
throw interruptEx
}
}
Declarative approach (UPDATED 11/2019):
The same, but within a script {} block in the steps of the stage. Not the neatest solution but the one that I've tested and got working.
At the time of the original answer there was no aborted or cleanup post-conditions (and IIRC only pipeline had post-conditions, but stage didn't).
According to Jenkins Declarative Pipeline docs, under post section:
cleanupRun 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()
}
}
}
}
}
回答2:
You can add a post trigger "cleanup" to the stage:
post {
cleanup {
script { ... }
sh "remove lock"
}
}
来源:https://stackoverflow.com/questions/43599268/how-to-catch-manual-ui-cancel-of-job-in-jenkinsfile