小编典典

在管道工作流程中使用Jenkins'Mailer'

jenkins

我想在一个定义管道构建作业的框架中利用Jenkins
的现有Mailer插件Jenkinsfile。给定以下简单的失败脚本,我希望每个构建版本都会收到一封电子邮件。

#!groovy

stage 'Test'
node {
    try {
        sh 'exit 1'
    } finally {
        step([$class: 'Mailer', notifyEveryUnstableBuild: true, recipients: 'me@me.com', sendToIndividuals: true])
    }
}

构建的输出为:

Started by user xxxxx
[Pipeline] stage (Test)
Entering stage Test
Proceeding
[Pipeline] node
Running on master in /var/lib/jenkins/jobs/rpk-test/workspace
[Pipeline] {
[Pipeline] sh
[workspace] Running shell script
+ exit 1
[Pipeline] step
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
ERROR: script returned exit code 1
Finished: FAILURE

如您所见,它确实记录了它step在失败后立即执行管道的过程,但是没有生成电子邮件。

利用自由工作的其他自由式工作中的电子邮件mailer,只是通过管道工作来调用。

这与Jenkins 2.2和mailer 1.17一起运行。

是否有其他机制可以用来调用失败的构建电子邮件? 我不需要该mail步骤的所有开销,仅需要有关故障和恢复的通知。


阅读 274

收藏
2020-07-25

共1个答案

小编典典

在Pipeline中,失败sh不会立即将设置为currentBuild.resultFAILURE而初始值为null。因此,依赖于诸如Mailer之类的构建状态的构建步骤可能看起来不正确。

您可以通过添加调试打印来检查它:

stage 'Test'
node {
    try {
        sh 'exit 1'
    } finally {
        println currentBuild.result  // this prints null
        step([$class: 'Mailer', notifyEveryUnstableBuild: true, recipients: 'me@me.com', sendToIndividuals: true])
    }
}

整个流程都由Jenkins提供的异常处理程序包装,这就是Jenkins最终将构建标记为失败的原因。

因此,如果您想使用Mailer,则需要正确维护构建状态。例如:

stage 'Test'
node {
    try {
        sh 'exit 1'
        currentBuild.result = 'SUCCESS'
    } catch (any) {
        currentBuild.result = 'FAILURE'
        throw any //rethrow exception to prevent the build from proceeding
    } finally {
        step([$class: 'Mailer', notifyEveryUnstableBuild: true, recipients: 'me@me.com', sendToIndividuals: true])
    }
}

如果您不需要重新抛出异常,则可以使用catchError。它是内置的Pipeline,可捕获其范围内的任何异常,将其打印到控制台中并设置构建状态。例:

stage 'Test'
node {
    catchError {
        sh 'exit 1'
    } 
    step([$class: 'Mailer', notifyEveryUnstableBuild: true, recipients: 'me@me.com', sendToIndividuals: true])
}
2020-07-25