39

如何在构建失败时向 Jenkins 管道添加旧式构建后任务,该任务会发送电子邮件?我在管道的 GUI 中找不到“构建后操作”。我知道我可以包装整个构建脚本 try/catch,但是,当构建脚本很大并且即使手动中止作业时仍继续发送电子邮件时,这似乎很难看。我想实现与之前email-ext基于构建后操作相同的功能。

try {
    // Do sth
} catch(e) {
    emailext body: '$DEFAULT_CONTENT', 
        recipientProviders: [
            [$class: 'CulpritsRecipientProvider'],
            [$class: 'DevelopersRecipientProvider'],
            [$class: 'RequesterRecipientProvider']
        ], 
        replyTo: '$DEFAULT_REPLYTO', 
        subject: '$DEFAULT_SUBJECT',
        to: '$DEFAULT_RECIPIENTS'
    throw err
}
4

6 回答 6

55

这个答案适用于我的 Jenkins 版本。2.96。

Jenkins管道电子邮件未在构建失败时发送 - Thinbug

 pipeline {  
     agent any  
     stages {  
         stage('Test') {  
             steps {  
                 sh 'echo "Fail!"; exit 1'  
             }  
         }  
     }  
     post {  
         always {  
             echo 'This will always run'  
         }  
         success {  
             echo 'This will run only if successful'  
         }  
         failure {  
             mail bcc: '', body: "<b>Example</b><br>Project: ${env.JOB_NAME} <br>Build Number: ${env.BUILD_NUMBER} <br> URL de build: ${env.BUILD_URL}", cc: '', charset: 'UTF-8', from: '', mimeType: 'text/html', replyTo: '', subject: "ERROR CI: Project name -> ${env.JOB_NAME}", to: "foo@foomail.com";  
         }  
         unstable {  
             echo 'This will run only if the run was marked as unstable'  
         }  
         changed {  
             echo 'This will run only if the state of the Pipeline has changed'  
             echo 'For example, if the Pipeline was previously failing but is now successful'  
         }  
     }  
 }
于 2017-12-19T07:51:27.237 回答
26

只有在构建状态发生变化时才采取行动,您可以使用post > changed block

对于检查,状态已更改为您可以使用脚本块结合检查currentBuild.currentResult属性值的状态。

像这样:

pipeline {
    ...

    post {
        changed {
            script {
                if (currentBuild.currentResult == 'FAILURE') { // Other values: SUCCESS, UNSTABLE
                    // Send an email only if the build status has changed from green/unstable to red
                    emailext subject: '$DEFAULT_SUBJECT',
                        body: '$DEFAULT_CONTENT',
                        recipientProviders: [
                            [$class: 'CulpritsRecipientProvider'],
                            [$class: 'DevelopersRecipientProvider'],
                            [$class: 'RequesterRecipientProvider']
                        ], 
                        replyTo: '$DEFAULT_REPLYTO',
                        to: '$DEFAULT_RECIPIENTS'
                }
            }
        }
    }

}
于 2017-08-31T22:17:42.550 回答
19

目前,您必须将此过程与try-一起使用catch以获取构建后操作。

但在未来,这一步是计划好的(实际上它正在审查中)。您可以阅读博客文章以获取更多信息(请参阅声明性管道部分)。另请参阅Jenkins Jira 票证拉取请求

更新:

Jenkins 声明式管道现在具有post将在每次构建结束时有条件地运行步骤的部分。 有关更多信息,请参阅文档

post {
 always {
   sh 'echo "This will always run"'
 }
 success {
  sh 'echo "This will run only if successful"'
 }
 failure {
  sh 'echo "This will run only if failed"'
 }
 unstable {
  sh 'echo "This will run only if the run was marked as unstable"'
 }
 changed {
  sh 'echo "This will run only if the state of the Pipeline has changed"'
  sh 'echo "For example, the Pipeline was previously failing but is now successful"'
  sh 'echo "... or the other way around :)"'
 }
}
于 2016-10-01T11:15:55.673 回答
10

这在我的 Jenkins(当前版本 2.164.2 和 emailext)上运行良好,带有声明性管道:

pipeline {
...

environment {
        EMAIL_TO = 'someone@host.com'
    }
post {
        failure {
            emailext body: 'Check console output at $BUILD_URL to view the results. \n\n ${CHANGES} \n\n -------------------------------------------------- \n${BUILD_LOG, maxLines=100, escapeHtml=false}', 
                    to: "${EMAIL_TO}", 
                    subject: 'Build failed in Jenkins: $PROJECT_NAME - #$BUILD_NUMBER'
        }
        unstable {
            emailext body: 'Check console output at $BUILD_URL to view the results. \n\n ${CHANGES} \n\n -------------------------------------------------- \n${BUILD_LOG, maxLines=100, escapeHtml=false}', 
                    to: "${EMAIL_TO}", 
                    subject: 'Unstable build in Jenkins: $PROJECT_NAME - #$BUILD_NUMBER'
        }
        changed {
            emailext body: 'Check console output at $BUILD_URL to view the results.', 
                    to: "${EMAIL_TO}", 
                    subject: 'Jenkins build is back to normal: $PROJECT_NAME - #$BUILD_NUMBER'
        }
    }
}

您可以控制构建失败或状态更改的电子邮件。我还把构建日志放到了电子邮件正文中

于 2019-04-11T16:56:14.697 回答
1

干燥您的脚本化管道,您可以使用自己的共享库轻松扩展 Jenkins,并定义一个自定义步骤emailOnError,例如

def call(Closure action) {
    try {
        action()
    } catch(e){
        emailext    body: '$DEFAULT_CONTENT', 
                    recipientProviders: [
                        [$class: 'DevelopersRecipientProvider'],
                        [$class: 'RequesterRecipientProvider']
                    ], 
                    replyTo: '$DEFAULT_REPLYTO', 
                    subject: '$PROJECT_NAME - Build # $BUILD_NUMBER - ERROR!',
                    to: '$DEFAULT_RECIPIENTS'
        throw err
    }   
}

然后像使用它

emailOnError() {
    // Do sth   
}
于 2020-06-24T08:52:55.713 回答
1

几乎所有上述答案都是正确的,但是当构建失败时,我在帖子部分中使用了这个答案。也许这可能有用

post {
always {
  script {
    if (currentBuild.currentResult == 'FAILURE') {
      step([$class: 'Mailer', notifyEveryUnstableBuild: true, recipients: "abc.xyz@blabl.com", sendToIndividuals: true])
    }
  }
}
于 2020-06-24T09:19:41.113 回答