2017-06-02 107 views
2

我想将现有的Jenkins管道转换为新的声明式管道,我想知道如何正确处理邮件通知?如何在Jenkins声明式管道中发送“恢复正常”通知?

我目前使用此代码:

node { 
    try { 

     ... 

     currentBuild.result = 'SUCCESS' 
    } catch (any) { 
     currentBuild.result = 'FAILURE' 
     throw any 
    } finally { 
     step([$class: 'Mailer', 
      notifyEveryUnstableBuild: true, 
      recipients: "[email protected]", 
      sendToIndividuals: true]) 
    } 
} 

它运作良好,但我不明白如何使用新的声明语法这一点。我认为可以通过使用post()和不同的通知来完成,但我不知道如何。我试过这个:

post { 
    always { 
     step([$class: 'Mailer', 
      notifyEveryUnstableBuild: true, 
      recipients: "[email protected]", 
      sendToIndividuals: true]) 
    } 
} 

但问题是,它不会发送任何“回到正常”的邮件。

如何在Jenkins声明式管道中使用Mailer插件来发送“回到正常”邮件?

应该再次使用围绕所有声明语法的try/catch?

回答

2

问题是,在声明中currentBuild.result后段没有被设置为SUCCESS。尽管已经设置了FAILURE和ABORTED。所以这里的行为似乎目前不一致。

我已经改善从How to get same Mailer behaviour for Jenkins pipeline我的答案来处理这种情况更好:

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: "[email protected]", 
      sendToIndividuals: true]) 
     } 
    } 
} 
4

可以查看以前的版本像一个全明星:

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']] 
      ) 
      } 
     } 
     } 
    } 
    } 
} 
2

发送邮件时生成失败。当构建成功时,您将检查以前的构建是否成功。如果不是,你会发送一封邮件告诉用户它再次工作。

post { 

     failure { 
      mail to: '[email protected]', 
      subject: "Failed Pipeline: ${currentBuild.fullDisplayName}", 
      body: "Build failed: ${env.BUILD_URL}" 
     } 

     success { 
      if (currentBuild.previousBuild != null && currentBuild.previousBuild.result != 'SUCCESS') { 
       mail to: '[email protected]', 
       subject: "Pipeline Success: ${currentBuild.fullDisplayName}", 
       body: "Build is back to normal (success): ${env.BUILD_URL}"  
      }   
     } 
    } 
相关问题