主要代码
def checkpoint = fileLoader.fromGit() // 实现你自己的 jenkins checkpoint // 我们发送的内容为 build 链接 String emailContent = "${env.BUILD_URL}" // 获取 email 收件人, 默认为相关干系人 def to = emailextrecipients([ [$class: 'CulpritsRecipientProvider'], [$class: 'DevelopersRecipientProvider'], [$class: 'RequesterRecipientProvider'] ]) // 给 Jenkins 一个 build 参数, 默认发送的邮箱 String defaultToEmail = "${NOTIFACATION_EMAIL}" Closure sendEmail = { stageName -> String body = """ STEP: $stageName DETAIL: $emailContent """ if (to == null || to == "") { echo "发送邮件的列表 ${to}, 默认发送给 ${defaultToEmail}" to = defaultToEmail } echo "发邮件给 ${to} 所在步骤 ${stageName} 内容 ${emailContent}" mail body: body, from: "someEmail@Alfred", subject: " Jenkins 挂啦" to:to } Closure stageEmailFailure = { nodeLabel, stageName, closure -> try { checkpoint.stage(stageName) { node(nodeLabel) { closure.call() } } } catch (InterruptedException ire) { echo " Jenkins 被终止" currentBuild.result = "ABORTED" throw ire } catch (err) { sendEmail.call(stageName) throw err } } stageEmailFailure("buildSlaveLabel", "Build", { // 你的 build 脚本 })
坑点
- 出现 java.lang.NoSuchMethodError: No such DSL method ‘$’ found among …
- 出现 Scripts not permitted to use method java.lang.String is Empty
- 出现 手动点击 Abort 终止后并未终止, 表象只是 skip 跳过了而已
原因以及解决方案:
- 在闭包 Closure 中, 并不能直接使用外部环境变量, 也不能直接用${}包裹外部没有显示定义的变量. 只能在闭包外面先定义好, 再传入. 或者在外部显示申明.
- 官网 email-ext plugin 插件 emailextrecipients 的列子, 得到的 to, 使用了 to.isEmpty(). 但由于大部分权限问题无法使用. 解决方案就是避免使用就好.
- 在 try catch 中记得再次抛出异常即可.
步奏->步骤
Thanks Updated