We use Jenkins Pipeline shared library custom steps in our build files.
We have a use case where the custom step will perform a potentially long-running operation; one that we want to ensure has 'cleanup' logic in case of failure. However, we are unsure how to perform the cleanup logic in the case that the top level build is aborted (manually, via timeout, etc).
Custom step:
// myTask.groovy
void call(Map config = [:]) {
// long running task that needs cleanup at the end
}
Build file:
@Library('my-library') _
pipeline {
agent { label 'build' }
options {
timeout(time: 1, unit: 'HOURS')
}
stages {
stage('Long running task') {
steps {
myTask()
}
}
}
}
We are aware of post
conditions (e.g. unsuccessful
) that can be used to handle logic on failure, but we are hoping there is a way to handle this from within the custom step so that all logic for such can be encapsulated in a single place. Otherwise, the logic for cleanup needs to be handled separately in the post
condition.
Is this possible?
We use Jenkins Pipeline shared library custom steps in our build files.
We have a use case where the custom step will perform a potentially long-running operation; one that we want to ensure has 'cleanup' logic in case of failure. However, we are unsure how to perform the cleanup logic in the case that the top level build is aborted (manually, via timeout, etc).
Custom step:
// myTask.groovy
void call(Map config = [:]) {
// long running task that needs cleanup at the end
}
Build file:
@Library('my-library') _
pipeline {
agent { label 'build' }
options {
timeout(time: 1, unit: 'HOURS')
}
stages {
stage('Long running task') {
steps {
myTask()
}
}
}
}
We are aware of post
conditions (e.g. unsuccessful
) that can be used to handle logic on failure, but we are hoping there is a way to handle this from within the custom step so that all logic for such can be encapsulated in a single place. Otherwise, the logic for cleanup needs to be handled separately in the post
condition.
Is this possible?
Share Improve this question asked Mar 29 at 20:38 trebortrebor 1,0331 gold badge15 silver badges30 bronze badges 3- Can you consider to use a try-catch? You can see here: jenkins.io/doc/pipeline/steps/workflow-basic-steps/… – Marco Caberletti Commented Mar 29 at 22:06
- I think that would need to be logic in the main build pipeline file and not the custom step (groovy), right? – trebor Commented Mar 30 at 1:30
- You can use it inside your custom step – Marco Caberletti Commented Mar 30 at 7:39
1 Answer
Reset to default 1Thanks to @marco's comment, this is a simple answer!
A try
block can be used in the custom step and it allows catching even top-level Jenkins exceptions:
// myTask.groovy
void call(Map config = [:]) {
try {
// long running task
} finally {
// perform cleanup
}
}
In our case, this even catches the exception thrown from our use of the Build Timeout plugin.