发送关于Jenkins管道故障的电子邮件

ncecgwcz  于 2023-10-17  发布在  Jenkins
关注(0)|答案(6)|浏览(164)

我如何向Jenkins管道添加一个旧式的构建后任务,当构建失败时发送电子邮件?我在GUI中找不到管道的“构建后操作”。我知道我可以 Package 整个构建脚本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
}
6yt4nkrj

6yt4nkrj1#

这个答案在我的Jenkins版本中起作用。2.96.
Jenkins pipeline email not sent on build failure - Stack Overflow

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: "[email protected]";  
         }  
         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'  
         }  
     }  
 }

mail步骤的官方文档

vnzz0bqm

vnzz0bqm2#

如果只在构建状态发生变化时才采取行动,可以使用post > changed块。
为了检查状态更改为什么状态,您可以使用脚本块结合检查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'
                }
            }
        }
    }

}
fgw7neuy

fgw7neuy3#

目前,您必须使用try-catch的此过程来获取构建后操作。
但在未来,这一步骤是有计划的(实际上是在审查中)。您可以阅读the blog post以获取更多信息(参见声明性管道部分)。另见the Jenkins Jira ticketthe pull request

更新:

Jenkins声明性管道现在有post部分,它将在每次构建结束时有条件地运行步骤。See the docs更多信息

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 :)"'
 }
}
sc4hvdpw

sc4hvdpw4#

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

pipeline {
...

environment {
        EMAIL_TO = '[email protected]'
    }
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'
        }
    }
}

您可以控制生成失败或状态更改的电子邮件。此外,我把构建日志的电子邮件体

rfbsl7qr

rfbsl7qr5#

几乎所有以上的答案都是正确的,但这一个我用在后部分时,建设失败。也许这会有用

post {
always {
  script {
    if (currentBuild.currentResult == 'FAILURE') {
      step([$class: 'Mailer', notifyEveryUnstableBuild: true, recipients: "[email protected]", sendToIndividuals: true])
    }
  }
}
jxct1oxe

jxct1oxe6#

为了DRY你的脚本管道,你可以轻松地用你自己的共享库扩展Jenkins,并通过创建vars/emailOnError.groovy来定义一个自定义步骤 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来自vars/emailOnError.groovy,可以这样使用:

emailOnError() {
    // Do sth   
}

相关问题