尽早停止詹金斯管道的工作 [英] Halt a jenkins pipeline job early

查看:150
本文介绍了尽早停止詹金斯管道的工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Jenkins Pipeline工作中,我们有两个阶段,我想要的是,如果其中任何一个阶段失败,那么停止构建,而不继续进行下一个阶段.

In our Jenkins Pipeline job we have a couple of stages, and what I would like is if any of the stages fail, then to have the build stop and not continue on to the further stages.

以下是其中一个阶段的示例:

Here's an example of one of the stages:

stage('Building') {
    def result = sh returnStatus: true, script: './build.sh'
    if (result != 0) {
        echo '[FAILURE] Failed to build'
        currentBuild.result = 'FAILURE'
    }
}

脚本将失败,并且生成结果将更新,但是作业将继续进行到下一个阶段.发生这种情况时,我该如何终止或停止工作?

The script will fail, and the build result will update, but the job continues on to the next stages. How can I abort or halt the job when this happens?

推荐答案

基本上,这就是sh步骤的作用.如果不将结果捕获到变量中,则可以运行:

Basically that is what the sh step does. If you do not capture the result in a variable, you can just run:

sh "./build"

如果脚本重新生成非零的退出代码,则会退出.

This will exit if the script reurns a non-zero exit code.

如果您需要先做一些事情并需要捕获结果,则可以使用shell步骤退出工作

If you need to do stuff first, and need to capture the result, you can use a shell step to quit the job

stage('Building') {
    def result = sh returnStatus: true, script: './build.sh'
    if (result != 0) {
        echo '[FAILURE] Failed to build'
        currentBuild.result = 'FAILURE'
        // do more stuff here

        // this will terminate the job if result is non-zero
        // You don't even have to set the result to FAILURE by hand
        sh "exit ${result}"  
    }
}

但是以下内容会给您带来相同的效果,但似乎更理智

But the following will give you the same, but seems more sane to do

stage('Building') {
    try { 
         sh './build.sh'
    } finally {
        echo '[FAILURE] Failed to build'
    }
}

还可以在您的代码中调用return.但是,如果您在stage内部,它将仅退出该阶段.所以

It is also possible to call return in your code. However if you are inside a stage it will only return out of that stage. So

stage('Building') {
   def result = sh returnStatus: true, script: './build.sh'
   if (result != 0) {
      echo '[FAILURE] Failed to build'
      currentBuild.result = 'FAILURE'
      return
   }
   echo "This will not be displayed"
}
echo "The build will continue executing from here"

不会退出工作,但是

stage('Building') {
   def result = sh returnStatus: true, script: './build.sh'
}
if (result != 0) {
  echo '[FAILURE] Failed to build'
  currentBuild.result = 'FAILURE'
  return
}

会.

这篇关于尽早停止詹金斯管道的工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆