简体   繁体   English

如何在Jenkins管道构建失败后发送Slack通知?

[英]How to send Slack notification after Jenkins pipeline build failed?

I have a pipeline groovy script in Jenkins v2.19. 我在Jenkins v2.19中有一个管道groovy脚本。 Also I have a 我也有
"Slack Notification Plugin" v2.0.1 and "Groovy Postbuild Plugin". “Slack Notification Plugin”v2.0.1和“Groovy Postbuild Plugin”。

I have successfully send a message "build started" and "build finished" (if it had). 我已成功发送消息“build started”和“build finished”(如果有的话)。

When some build step failed – how I can send a message "Build failed" to the Slack channel? 当一些构建步骤失败时 - 我如何向Slack通道发送消息“Build failed”?

You could do something like this and use a try catch block. 你可以做这样的事情并使用try catch块。

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 完整的片段可以在这里找到Jenkinsfile模板

Based on Liam Newman's blog post , have a look at this cleaned up snippet for Slack only in scripted pipelines (declarative pipeline users scroll down). 根据Liam Newman的博客文章 ,仅在脚本管道中查看这个已清理的Slack片段(声明性管道用户向下滚动)。 It uses original Jenkins results , message formatting, better colors (based on EclEmma ), and some Groovy features like default arguments : 它使用原始的Jenkins结果 ,消息格式,更好的颜色(基于EclEmma ),以及一些Groovy功能,如默认参数

def notifySlack(String buildStatus = 'STARTED') {
    // Build status of null means success.
    buildStatus = buildStatus ?: 'SUCCESS'

    def color

    if (buildStatus == 'STARTED') {
        color = '#D4DADF'
    } else if (buildStatus == 'SUCCESS') {
        color = '#BDFFC3'
    } else if (buildStatus == 'UNSTABLE') {
        color = '#FFFE89'
    } else {
        color = '#FF9FA1'
    }

    def msg = "${buildStatus}: `${env.JOB_NAME}` #${env.BUILD_NUMBER}:\n${env.BUILD_URL}"

    slackSend(color: color, message: msg)
}

node {
    try {
        notifySlack()

        // Existing build steps.
    } catch (e) {
        currentBuild.result = 'FAILURE'
        throw e
    } finally {
        notifySlack(currentBuild.result)
    }
}

The output will be something like this (play around with different formatting styles here ): 输出将是这样的(在这里玩不同的格式样式):

在此输入图像描述

Maybe env.JOB_NAME contains encoded slashes ( %2F ) which can be fixed with replaceAll("%2F", "/") . 也许env.JOB_NAME包含编码斜杠( %2F ),可以使用replaceAll("%2F", "/")修复。 Check out this Gist to see how to notify HipChat as well. 看看这个要点 ,看看如何通知HipChat。

If you have a declarative pipeline, have a look at the Jenkins documentation on "Cleaning up and notifications" or Liam Newman's follow-up post "Declarative Pipeline: Notifications and Shared Libraries" . 如果您有声明性管道,请查看关于“清理和通知”的Jenkins文档或Liam Newman的后续帖子“声明性管道:通知和共享库”

Just in case if in Declarative Syntax, 以防万一在声明式语法中,

Now, Jenkins provides post . 现在,詹金斯提供了post You can check result at the end of pipeline. 您可以在管道末尾检查结果。

https://jenkins.io/doc/book/pipeline/syntax/#post-example https://jenkins.io/doc/book/pipeline/syntax/#post-example

Using like: 使用像:

pipeline {
    stages { ... }
    post {
       // only triggered when blue or green sign
       success {
           slackSend ...
       }
       // triggered when red sign
       failure {
           slackSend ...
       }
       // trigger every-works
       always {
           slackSend ...
       }
    }
}

It would be used in every stage also. 它也将在每个stage使用。 See the document link please. 请参阅文档链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM