早点停止jenkins管道工作

时间:2016-12-01 19:21:11

标签: jenkins jenkins-pipeline

在我们的詹金斯管道工作中,我们有几个阶段,如果任何阶段失败,我想要的是,然后让构建停止,而不是继续进一步的阶段。

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

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

脚本将失败,构建结果将更新,但作业将继续进行下一阶段。如果发生这种情况,我该如何中止或停止工作?

3 个答案:

答案 0 :(得分:11)

基本上这就是sh步骤的作用。如果您没有在变量中捕获结果,则可以运行:

sh "./build"

如果脚本重新出现非零退出代码,则会退出。

如果您需要先做东西,并且需要捕获结果,可以使用shell步骤退出作业

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}"  
    }
}

但是以下内容会给你相同的,但似乎更明白

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

也可以在代码中调用return。但是,如果您在stage内,它将只返回该阶段。所以

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
}

意愿。

答案 1 :(得分:7)

实现此行为的另一种方法是抛出异常。事实上,这正是詹金斯本身所做的。这样,您还可以将构建状态设置为ABORTEDFAILURE。此示例中止构建:

stage('Building') {
    currentBuild.rawBuild.result = Result.ABORTED
    throw new hudson.AbortException('Guess what!')
    echo 'Further code will not be executed'
}

输出:

[Pipeline] stage
[Pipeline] { (Building)
[Pipeline] }
[Pipeline] // stage
[Pipeline] End of Pipeline
ERROR: Guess what!
Finished: ABORTED

答案 2 :(得分:1)

自Jenkins v2起,这也应该起作用

error('Failed to build')

工作将以:

结尾
ERROR: Failed to build
Finished: ERROR