我有一個Jenkinsfile與多個階段,其中一個實際上是另一個工作(部署之一),在某些情況下可能會失敗。如何在Jenkins管道中爲失敗階段實施重試選項?
我知道我可以使用Jenkinsfile做出提示,但我不知道如何實現此作業的重試機制。
我有一個Jenkinsfile與多個階段,其中一個實際上是另一個工作(部署之一),在某些情況下可能會失敗。如何在Jenkins管道中爲失敗階段實施重試選項?
我知道我可以使用Jenkinsfile做出提示,但我不知道如何實現此作業的重試機制。
你應該能夠結合重試+輸入要做到這一點 類似的東西
stage('deploy-test') {
try {
build 'yourJob'
} catch(error) {
echo "First build failed, let's retry if accepted"
retry(2) {
input "Retry the job ?"
build 'yourJob'
}
}
}
你也可以,如果你想它完成,如果沒有人驗證使用超時輸入。 還有最好推遲,可能是有用的,但我還沒有使用它
編輯: 最好推遲似乎肯定是最好的,你應該用它玩一下,但這樣的事情是清潔:
stage('deploy-test') {
waitUntil {
try {
build 'yourJob'
} catch(error) {
input "Retry the job ?"
false
}
}
}
順便說一下,有這裏所有的步驟https://jenkins.io/doc/pipeline/steps
這個要點(不是我的)是我發現,同時試圖實現這個功能的更好的選擇之一。 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)上發佈。
該總體功能請求位於[JENKINS-33846](https://issues.jenkins-ci.org/browse/JENKINS-33846)。它(dissapointingly)僅在[JENKINS-45455](https://issues.jenkins-ci.org/browse/JENKINS-45455)中的聲明性管道中選擇。 – mkobit