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

Jay*_*ang 6 jenkins jenkins-pipeline

我的 Jenkins 管道并行运行多个任务。似乎如果一个阶段失败,所有后续阶段都将运行它们的failurepost 块(无论它们是否真的失败了)。我不知道这是设计使然还是我做错了什么。

注意:此管道在 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')
                        }
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在上面的管道中,只有“失败阶段”失败,但在输出中我看到了这一点,表明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
Run Code Online (Sandbox Code Playgroud)

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

Jay*_*ang 4

看起来这是声明式管道的一个已知 错误。我不得不放弃使用内置的 post->failure 块并使用 try/catch 来代替,这有它自己的问题:

  1. 您必须捕获并重新抛出错误,以使阶段适当地失败。
  2. 用户界面可能会有点混乱,因为失败的步骤不再以红色突出显示(但错误消息仍在日志中)。
  3. 代码的可读性稍差。

这段代码工作正常。只有失败阶段才会回显“检测到的失败”,而不是两者。

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)
                            }
                        }
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)