How to send Slack notification after Jenkins pipeline build failed?

后端 未结 3 502
情书的邮戳
情书的邮戳 2020-12-23 16:48

I have a pipeline groovy script in Jenkins v2.19. Also I have a
\"Slack Notification Plugin\" v2.0.1 and \"Groovy Postbuild Plugin\".

I have successfully send a

3条回答
  •  我在风中等你
    2020-12-23 17:35

    You could do something like this and use a try catch block.

    Here is some example Code:

    node {
        try {
            notifyBuild('STARTED')
    
            stage('Prepare code') {
                echo 'do checkout stuff'
            }
    
            stage('Testing') {
                echo 'Testing'
                echo 'Testing - publish coverage results'
            }
    
            stage('Staging') {
                echo 'Deploy Stage'
            }
    
            stage('Deploy') {
                echo 'Deploy - Backend'
                echo 'Deploy - Frontend'
            }
    
      } catch (e) {
        // If there was an exception thrown, the build failed
        currentBuild.result = "FAILED"
        throw e
      } finally {
        // Success or failure, always send notifications
        notifyBuild(currentBuild.result)
      }
    }
    
    def notifyBuild(String buildStatus = 'STARTED') {
      // build status of null means successful
      buildStatus =  buildStatus ?: 'SUCCESSFUL'
    
      // Default values
      def colorName = 'RED'
      def colorCode = '#FF0000'
      def subject = "${buildStatus}: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'"
      def summary = "${subject} (${env.BUILD_URL})"
    
      // Override default values based on build status
      if (buildStatus == 'STARTED') {
        color = 'YELLOW'
        colorCode = '#FFFF00'
      } else if (buildStatus == 'SUCCESSFUL') {
        color = 'GREEN'
        colorCode = '#00FF00'
      } else {
        color = 'RED'
        colorCode = '#FF0000'
      }
    
      // Send notifications
      slackSend (color: colorCode, message: summary)
    }
    

    Complete snippet can be found here Jenkinsfile Template

提交回复
热议问题