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

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

问题描述

在我们的 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天全站免登陆