如何从Jenkins管道脚本发送自定义模板化电子邮件?

时间:2018-01-10 19:34:16

标签: jenkins groovy jenkins-pipeline

我希望Jenkins Pipeline作业在失败时发送自定义电子邮件报告。发送自定义电子邮件非常简单:

mail(
  to: 'recipient@example.com',
  from: 'no-reply@example.com', 
  replyTo: 'no-reply@example.com', 
  subject: 'your custom jenkins report', 
  body: 'custom report here',
)

但是,我想呈现某种模板并将其注入到邮件正文中。我并不关心使用什么模板语言(Jinja,ERB,还有其他什么......?)。我想把我的模板放在一个git存储库中。我怎样才能做到这一点?我正在考虑这些问题:

checkout([
  $class: 'GitSCM',
  userRemoteConfigs: [[url: 'https://git.example.com/custom-report.git']],
  branches: [[name: '*/master']],
])

reportBody = renderTemplate(file: 'custom-report/custom-report.template')

mail(
  to: 'recipient@example.com',
  from: 'no-reply@example.com', 
  replyTo: 'no-reply@example.com', 
  subject: 'your custom jenkins report', 
  body: reportBody,
)

1 个答案:

答案 0 :(得分:2)

我能够使用shared library执行此操作(虽然共享库不是必需的;您可以直接将这些步骤放入您的管道中,但它确实使一些事情稍微方便一些)。我使用以下文件创建了一个全局共享库:

resources/report.txt.groovy

Hello from ${job}!

vars/helpers.groovy

import groovy.text.StreamingTemplateEngine

def renderTemplate(input, variables) {
  def engine = new StreamingTemplateEngine()
  return engine.createTemplate(input).make(variables).toString()
}

然后,在我的管道中,我添加了以下步骤:

variables = [ job: currentBuild.rawBuild.getFullDisplayName() ]
template = libraryResource('report.txt.groovy')
report = helpers.renderTemplate(template, variables)

mail(
  to: 'recipient@example.com',
  from: 'no-reply@example.com', 
  replyTo: 'no-reply@example.com', 
  subject: 'your custom jenkins report', 
  body: report,
)

这会生成一封包含以下内容的电子邮件:

Hello from SIS Unix Automation Testing » myjob » master #29!

其中SIS Unix Automation Testing » myjob » master是我的Multibranch Pipeline作业的全名。

请注意,您需要禁用沙箱或批准/白名单脚本才能使用此方法,否则StreamingTemplateEngine的某些内部内容将被阻止。

StreamingTemplateEngine的文档可用here

相关问题