这个要点(不是我的)也是我在尝试实现这个功能时发现的更好的选择之一。 https://gist.github.com/beercan1989/b66b7643b48434f5bdf7e1c87094acb9
将其更改为共享库中的一个方法,该方法只是根据我的需要重试或中止。还添加了最大重试次数并设置了超时变量,以便我们可以根据需要它的作业或阶段来更改它。
package com.foo.bar.jenkins
def class PipelineHelper {
def steps
PipelineHelper(steps) {
this.steps = steps
}
void retryOrAbort(final Closure<?> action, int maxAttempts, int timeoutSeconds, final int count = 0) {
steps.echo "Trying action, attempt count is: ${count}"
try {
action.call();
} catch (final exception) {
steps.echo "${exception.toString()}"
steps.timeout(time: timeoutSeconds, unit: 'SECONDS') {
def userChoice = false
try {
userChoice = steps.input(message: 'Retry?', ok: 'Ok', parameters: [
[$class: 'BooleanParameterDefinition', defaultValue: true, description: '', name: 'Check to retry from failed stage']])
} catch (org.jenkinsci.plugins.workflow.steps.FlowInterruptedException e) {
userChoice = false
}
if (userChoice) {
if (count <= maxAttempts) {
steps.echo "Retrying from failed stage."
return retryOrAbort(action, maxAttempts, timeoutMinutes, count + 1)
} else {
steps.echo "Max attempts reached. Will not retry."
throw exception
}
} else {
steps.echo 'Aborting'
throw exception;
}
}
}
}
}
示例用法,最多 2 次重试,等待 60 秒输入。
def pipelineHelper = new PipelineHelper(this)
stage ('Retry Example'){
pipelineHelper.retryOrAbort({
node{
echo 'Here is an example'
throw new RuntimeException('This example will fail.')
}
}, 2, 60)
}
只要记住将节点放在闭包内,这样等待输入就不会阻塞执行器。
如果你有付费的 jenkins,企业 Cloudbees 有一个 Checkpoint 插件可以更好地处理这个问题,但不打算为开源 Jenkins (JENKINS-33846) 发布。