首页 文章

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

提问于
浏览
1

当Jenkins的 Pipeline 构建失败时,我正在尝试发送电子邮件 . 可以在这里找到一个例子: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 回答

  • 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: '...'
    

相关问题