Jenkins 管道 - 在构建开始之前和构建之后自动发送电子邮件,而无需在 Jenkinsfile 中添加任何代码行

Jenkins pipeline - Automatically Send email before the build starts and after the build without adding any line of code in Jenkinsfile

目前我们在 Jenkinsfile 中使用 "send.notifyBuild('STATUS')"(注意 - notifyBuild 方法来自我们的全局库)。我想知道 Jenkins Multibranch Pipeline 项目是否能够在构建之前和之后默认发送电子邮件。甚至没有在 JenkinsFile 中指定一行代码。

node{
    try{
     stage ('Checkout'){
     checkout scm
     send.notifyBuild('STARTED')
     }

     stage ('Build'){
        sh "source ./environment.sh;mvn clean deploy"
     }

     send.notifyBuild('SUCCESSFUL')

     }catch(err){
        send.notifyBuild('FAILED')
        throw err
    }   


}

由于您已经在使用全局库,我建议将其添加到您的库中。这是格式化它的好方法:

node {
    withNotification {
        stage ('Checkout') {
            checkout scm
        }
        stage ('Build') {
            sh "source ./environment.sh;mvn clean deploy"
        }
    }
}

然后,在您的库的 vars/withNotification.groovy 文件中:

def call(Closure body) {
    send.notifyBuild('STARTED')
    try {
        body()
        send.notifyBuild('SUCCESSFUL')
    } catch (err) {
        send.notifyBuild('FAILED')
        error "Build failed, caught exception: ${err}"
    }
}

我发现这种模式对于低样板管道非常有用。