Bap*_*cht 6 email jenkins jenkins-pipeline
我正在尝试将现有的Jenkins管道转换为新的Declarative Pipeline,我想知道如何正确处理邮件通知?
我目前正在使用此代码:
node {
try {
...
currentBuild.result = 'SUCCESS'
} catch (any) {
currentBuild.result = 'FAILURE'
throw any
} finally {
step([$class: 'Mailer',
notifyEveryUnstableBuild: true,
recipients: "baptiste.wicht@gmail.com",
sendToIndividuals: true])
}
}
Run Code Online (Sandbox Code Playgroud)
它运行良好,但我没有看到如何使用新的声明性语法.我认为可以通过使用post()和不同的通知来完成某些事情,但我不确切知道如何.我试过这个:
post {
always {
step([$class: 'Mailer',
notifyEveryUnstableBuild: true,
recipients: "baptiste.wicht@gmail.com",
sendToIndividuals: true])
}
}
Run Code Online (Sandbox Code Playgroud)
但问题是它不会发送任何"恢复正常"的邮件.
如何在Jenkins声明性管道中使用Mailer插件才能发送"返回正常"邮件?
应该再次使用try/catch围绕所有声明性语法吗?
构建失败时发送邮件.当构建成功时,您将检查先前的构建是否成功.如果不是,您将发送邮件告诉用户它再次正常工作.
post {
failure {
mail to: 'user@mail.com',
subject: "Failed Pipeline: ${currentBuild.fullDisplayName}",
body: "Build failed: ${env.BUILD_URL}"
}
success {
if (currentBuild.previousBuild != null && currentBuild.previousBuild.result != 'SUCCESS') {
mail to: 'user@mail.com',
subject: "Pipeline Success: ${currentBuild.fullDisplayName}",
body: "Build is back to normal (success): ${env.BUILD_URL}"
}
}
}
Run Code Online (Sandbox Code Playgroud)
你可以像全明星一样检查以前的版本:
pipeline {
agent { label 'docker' }
stages {
stage ('build') {
steps {
sh 'ls'
}
}
}
post {
always {
script {
if (currentBuild.result == null || currentBuild.result == 'SUCCESS') {
if (currentBuild.previousBuild != null && currentBuild.previousBuild.result != 'SUCCESS') {
echo 'send your back to normal email here, maybe something like this, your mileage may vary'
emailext (
subject: "Back to normal: ${currentBuild.fullDisplayName}",
body: "Project is back to <blink>normal</blink>",
mimeType: 'text/html',
recipientProviders: [[$class: 'RequesterRecipientProvider'], [$class: 'DevelopersRecipientProvider']]
)
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在可以通过使用fixed后置条件(Documentation)来简化此操作。
这是我在沙盒管道项目中写的一个简单示例。
pipeline{
agent {
label 'Build'
}
stages{
stage('Build'){
steps{
script{
echo "Building..."
}
}
}
}
post{
success {
echo "Success"
}
failure {
echo "Failure"
}
fixed {
echo "Back to normal"
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,在声明的post部分中,currentBuild.result未设置为SUCCESS.虽然设置了FAILURE和ABORTED.所以此处的行为似乎不一致.
我已经改进了我的答案,如何为Jenkins管道获得相同的Mailer行为以更好地处理这种情况:
pipeline {
agent any
stages {
stage('test') {
steps {
echo 'some steps'
// error("Throw exception for testing purpose..")
}
}
}
post {
always {
script {
if (currentBuild.result == null) {
currentBuild.result = 'SUCCESS'
}
}
step([$class: 'Mailer',
notifyEveryUnstableBuild: true,
recipients: "test@test.com",
sendToIndividuals: true])
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4948 次 |
| 最近记录: |