如何在Jenkins声明性管道中检测哪个并行阶段失败?

时间:2018-03-19 18:54:43

标签: jenkins jenkins-pipeline

我的Jenkins管道并行运行多个任务。似乎如果一个阶段失败,所有后续阶段将运行他们的failure帖子阻止(无论他们实际上是否失败)。我不知道这是设计还是我做错了。

注意:此管道在Windows节点上运行,因此bat('exit /b 1')

pipeline {
    agent any

    stages {
        stage('Parallel steps') {
            parallel {
                stage('Successful stage') {
                    steps {
                        script { sleep 10 }
                    }
                    post {
                        failure {
                            echo('detected failure: Successful stage')
                        }
                    }
                }
                stage('Failure stage') {
                    steps {
                        script { bat('exit /b 1') }
                    }
                    post {
                        failure { 
                            echo('detected failure: Failure stage')
                        }
                    }
                }
            }
        }
    }
}

在上述渠道中,只有“失败”阶段'失败了,但在输出中我看到了这一点,表明两个步骤都执行了failure条件!

Started by user Doe, John
Running on WINDOWS_NODE in D:\workspace
[Successful stage] Sleeping for 10 sec
[Failure stage] [test] Running batch script
[Failure stage] D:\workspace>exit /b 1 
Post stage
[Pipeline] [Failure stage] echo
[Failure stage] detected failure: Failure stage
[Failure stage] Failed in branch Failure stage
Post stage
[Pipeline] [Successful stage] echo
[Successful stage] detected failure: Successful stage
ERROR: script returned exit code 1
Finished: FAILURE

我最好的方法是检测哪个并行阶段失败并将其报告给整个管道?

1 个答案:

答案 0 :(得分:1)

看起来这是带有声明性管道的known bug。我不得不放弃使用内置的post-gt;失败块并使用try / catch代替,这有其自身的问题:

  1. 你必须抓住然后重新抛出错误才能使舞台失败。
  2. UI可能会有点混乱,因为失败的步骤不再以红色突出显示(但错误消息仍在日志中)。
  3. 代码的可读性稍差。
  4. 此代码正常运行。只有失败的阶段才会回应“检测到失败”而不是两者。

    pipeline {
        agent any
    
        stages {
            stage('Parallel steps') {
                parallel {
                    stage('Successful stage') {
                        steps {
                            script {
                                try {
                                    sleep 10 
                                } catch (e) {
                                    echo('detected failure: Successful stage')
                                    throw(e)
                                }
                            }
                        }
                    }
                    stage('Failure stage') {
                        steps {
                            script {
                                try {
                                    bat('exit /b 1')
                                } catch (e) {
                                    echo('detected failure: Failure stage')
                                    throw(e)
                                }
                            }
                        }
                    }
                }
            }
        }
    }