Get error reason in Jenkinsfile failure

前端 未结 1 481
清酒与你
清酒与你 2021-01-18 06:47

I have the following post failure section:

   post {
        failure {
            mail subject: \"\\u2639 ${env.JOB_NAME} (${env.BUILD_NUMBER})         


        
相关标签:
1条回答
  • 2021-01-18 07:11

    I don't know of a way to retrieve the failure reason automatically out of thin air.

    However, you can use "post{ failure {" blocks in each phase to capture at least the phase in which it failed into a environment variable (e.g. env.FAILURE_REASON), and access that env var in the final (global scope) notification block.

    For more granularity, you can reuse the same mechanism of the global env variable, but use try { } catch { } blocks to capture which specific step failed.

    A generic example would be:

       pipeline {
         stages {
           stage('Build') {
             steps {
               ...
             }
             post {
               failure {
                 script { env.FAILURE_STAGE = 'Build' }
               }
             }
           }
           stage('Deploy') {
             steps {
               ...
             }
             post {
               failure {
                 script { env.FAILURE_STAGE = 'Deploy' }
               }
             }
           }
           ...
         }
         post {
            failure {
                mail subject: "\u2639 ${env.JOB_NAME} (${env.BUILD_NUMBER}) has failed",
                        body: """Build ${env.BUILD_URL} is failing in ${env.FAILURE_STAGE} stage!
                              |Somebody should do something about that""",
                          to: "devel@example.com",
                     replyTo: "devel@example.com",
                        from: 'jenkins@example.com'
            }
          }
        }
    

    Technically, you can even do some automated triage based on the failing stage and send a more targeted notification, or even create specific (e.g. Jira) tickets.

    For attaching the console log to the email notification, you'd want to look at emailext and the 'attachLog: true' attribute

    0 讨论(0)
提交回复
热议问题