我想利用现有的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.result
至FAILURE
而其初始值为 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/