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

标签 jenkins jenkins-plugins jenkins-pipeline

我想利用现有的Mailer来自 Jenkins 的插件位于定义管道构建作业的 Jenkinsfile 中。鉴于以下简单的失败脚本,我希望每次构建都会收到一封电子邮件。

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

正如您所看到的,它确实记录了在失败后立即执行管道步骤,但没有生成任何电子邮件。

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

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

是否有不同的机制可以调用失败的构建电子邮件?我不需要mail步骤的所有开销,只需要失败通知和回收率。

最佳答案

管道失败 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 。它是一个内置管道,可以捕获其范围内的任何异常,将其打印到控制台并设置构建状态。例如:

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

关于jenkins - 在管道工作流程中使用 Jenkins 'Mailer',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37169100/

相关文章:

json - 如何使用groovy修改jenkins工作区上的JSON属性?

Jenkins 管道可选 bool 参数

vb6 - Jenkins 管道 : build steps not running concurrently?

jenkins - 立即运行 Jenkins 作业

ant - Jenkins - 在另一份工作中使用一份工作的结果

ios - 自动为每个版本的TestFlight应用程序授予用户权限

jenkins - Jenkins 上的 JUnit 结果超过 1 个图表

java - 如果在第一个作业之后我们在控制台输出中获得了特定值,如何在 Jenkins 中运行第二个作业

git - 如何让slave系统访问Jenkins中的Git仓库

jenkins - 参数化Jenkins管道: Choices not showing up