Jenkins 文件在失败时发送电子邮件

Jenkins file send email on failure

我在 jenkins 上设置了多分支项目。 这是我的詹金斯文件:

properties([[$class: 'BuildDiscarderProperty', strategy: [$class: 'LogRotator', artifactDaysToKeepStr: '14', artifactNumToKeepStr: '10', daysToKeepStr: '14', numToKeepStr: '10']]])
node {
    checkout scm

    def lib = load 'cicd/shared-library.groovy'

    stage('build project') {
        lib.compileProject()
    }

    stage('Unit test') {
        lib.executeUnitTest()
    }

    stage('Archive log files') {
        def files = ["failure_services.txt", "unit_test.log"]
        lib.archiveFile(files, "unit_test_result.tar.xz")
    }

    stage('send email') {
        def subject = "Test Result"
        def content = 'ًLog file attached'
        def toList = ["aaa@gmail.com", "bbb@gmail.com"]
        def ccList = ["xxx@gmail.com", "zzz@gmail.com"]
        def attachmentFiles = ["unit_test_result.tar.xz"]
        lib.sendMail(toList, ccList, subject, content, attachmentFiles)
    }

    cleanWs()
}

有时 Unit test 阶段会导致错误,因此在这种情况下不会执行后续步骤。

我希望 send email 阶段在任何情况下都能执行。
如何在 JenkinsFile 上配置它?

很可能您只需要在管道中添加一个 post 部分。

The post section defines one or more additional steps that are run upon the completion of a Pipeline’s or stage’s run (depending on the location of the post section within the Pipeline). post can support any of the following post-condition blocks: always, changed, fixed, regression, aborted, failure, success, unstable, unsuccessful, and cleanup. These condition blocks allow the execution of steps inside each condition depending on the completion status of the Pipeline or stage. The condition blocks are executed in the order shown below.

在文档中查找更多信息here

在脚本管道(共享库)中,您可以在函数中定义发送电子邮件步骤。将您的管道步骤包装在 try-catch-finally 块中,并在 finally part.

中调用函数 send_email()

对于声明式管道,您可以将管道步骤包装在 catchError 块中并在其外部发送电子邮件。

示例:

properties([[$class: 'BuildDiscarderProperty', strategy: [$class: 'LogRotator', artifactDaysToKeepStr: '14', artifactNumToKeepStr: '10', daysToKeepStr: '14', numToKeepStr: '10']]])
node {
    catchError {
        checkout scm

        def lib = load 'cicd/shared-library.groovy'

        stage('build project') {
            lib.compileProject()
        }

        stage('Unit test') {
            lib.executeUnitTest()
        }

        stage('Archive log files') {
            def files = ["failure_services.txt", "unit_test.log"]
            lib.archiveFile(files, "unit_test_result.tar.xz")
        }
    }
    stage('send email') {
        def subject = "Test Result"
        def content = 'ًLog file attached'
        def toList = ["aaa@gmail.com", "bbb@gmail.com"]
        def ccList = ["xxx@gmail.com", "zzz@gmail.com"]
        def attachmentFiles = ["unit_test_result.tar.xz"]
        lib.sendMail(toList, ccList, subject, content, attachmentFiles)
    }

    cleanWs()
}