简体   繁体   English

脚本Jenkins管道:继续失败

[英]Scripted Jenkins pipeline: continue on fail

Is there a way to continue execution of the scripted pipeline even if the previous stage failed? 有没有办法继续执行脚本化管道,即使前一阶段失败了? I need to run specific commands (cleanup) when the build fails before the whole job fails. 我需要在整个作业失败之前构建失败时运行特定的命令(清理)。

The usual approach is to wrap your steps within a try block. 通常的方法是将您的步骤包装在try块中。

try {
  sh "..."
} catch (err) {
  echo "something failed"
}
// cleanup
sh "rm -rf *"

To ease the pain and make the pipeline code more readable, I've encapsulated this in another method here in my global library code . 为了减轻痛苦并使管道代码更具可读性,我在我的全局库代码中将其封装在另一个方法

Another approach, esp. 另一种方法,尤其是 created because of this very issue, are the declarative pipelines ( blog , presentation ). 因为这个问题而创建的是声明性管道博客演示 )。

The accepted answer wouldn't fail the stage or even mark it as unstable. 接受的答案不会失败,甚至将其标记为不稳定。 It is now possible to fail a stage, continue the execution of the pipeline and choose the result of the build: 现在可以使阶段失败,继续执行管道并选择构建的结果:

pipeline {
    agent any
    stages {
        stage('1') {
            steps {
                sh 'exit 0'
            }
        }
        stage('2') {
            steps {
                catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
                    sh "exit 1"
                }
            }
        }
        stage('3') {
            steps {
                sh 'exit 0'
            }
        }
    }
}

In the example above, all stages will execute, the pipeline will be successful, but stage 2 will show as failed: 在上面的示例中,所有阶段都将执行,管道将成功,但阶段2将显示为失败:

管道示例

As you might have guessed, you can freely choose the buildResult and stageResult , in case you want it to be unstable or anything else. 正如您可能已经猜到的那样,您可以自由选择buildResultstageResult ,以防您希望它不稳定或其他任何东西。 You can even fail the build and continue the execution of the pipeline. 您甚至可以使构建失败并继续执行管道。

Just make sure your Jenkins is up to date, since this is a fairly new feature. 只需确保你的Jenkins是最新的,因为这是一个相当新的功能。

  post {
    always {
      cleanWs()
    }
  }
}

Will always cleanup the job even if the rest fails 即使其余的失败,也会一直清理工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM