Jenkins Pipeline Groovy Script:在Jenkinsfile中使用`mail`

时间:2017-09-14 07:03:00

标签: jenkins groovy continuous-integration jenkins-pipeline continuous-delivery

我正在尝试在Jenkins上的管道构建失败时发送电子邮件。可以在此处找到一个示例:https://github.com/jenkinsci/pipeline-examples/blob/master/jenkinsfile-examples/nodejs-build-test-deploy-docker-notify/Jenkinsfile

我的具体 groovy 脚本如下所示:

#!groovy
node('') {
   def env = ["JAVA_HOME=${tool 'jdk1.8.0_131'}", "PATH+MAVEN=${tool 'maven_3.1.1'}/bin:${env.JAVA_HOME}/bin", "PATH+GRADLE=${tool 'gradle_4.1'}/bin:${env.JAVA_HOME}/bin" ]

   def err = null
   currentBuild.result = "SUCCESS"

  try {
   stage('errorStage') {
        dir('error') {
            git url: "unknown", branch: "master"
            withEnv(env) {
                sh "mvn -Pjenkins-build clean deploy"
            }
        }
    }
  } catch (caughtError) {
      println "caught error :" + caughtError
      err = caughtError
      currentBuild.result = "FAILURE"
      mail (body:
            "Pipeline error: ${err}\nFix me.",
            from: 'jenkins@x.com',
            subject: 'Pipeline build failed',
            to: 'recipient@x.com')
  } finally {
      /* Must re-throw exception to propagate error */
      if (err) {
          throw err
      }
  }

}

实际上,没有任何事情发生,尽管异常被正确捕获并且构建失败。有没有必要能够使用mail ?!也许是另一个Jenkins插件还是什么?

1 个答案:

答案 0 :(得分:1)

我能够通过在Jenkins而不是emailext上使用mail插件自行修复它。代码现在如下所示:

emailext body: "Pipeline error: ${err}\nPlease go to ${BUILD_URL} and verify the build",
                recipientProviders: [[$class: 'DevelopersRecipientProvider'], [$class: 'RequesterRecipientProvider']],
                subject: "'${JOB_NAME}' (${BUILD_NUMBER}) failed",
                to: '...'