我在Jenkins v2.19中有一个管道groovy脚本。我也有一个 " Slack Notification Plugin" v2.0.1和" Groovy Postbuild插件"。
我已成功发送消息" build build"并且"构建完成" (如果有)。
当某些构建步骤失败时 - 我如何发送消息"构建失败"到Slack频道?
答案 0 :(得分:34)
您可以执行类似的操作并使用try catch块。
以下是一些示例代码:
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)
}
可在此处找到完整代码段Jenkinsfile Template
答案 1 :(得分:21)
基于Liam Newman's blog post,只在脚本化管道中查看已清理的Slack片段(声明性管道用户向下滚动)。它使用原始Jenkins results,消息格式,更好的颜色(基于EclEmma),以及一些Groovy功能,如default arguments:
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)
}
}
输出将是这样的(使用不同的格式样式here):
也许env.JOB_NAME
包含编码的斜杠(%2F
),可以使用replaceAll("%2F", "/")
修复。查看this Gist以了解如何通知HipChat。
如果您有声明性管道,请查看"Cleaning up and notifications"或Liam Newman的后续帖子"Declarative Pipeline: Notifications and Shared Libraries"上的Jenkins文档。
答案 2 :(得分:8)
以防万一,如果是声明性语法,
现在,Jenkins提供了post
。您可以在管道末端检查结果。
https://jenkins.io/doc/book/pipeline/syntax/#post-example
使用like:
pipeline {
stages { ... }
post {
// only triggered when blue or green sign
success {
slackSend ...
}
// triggered when red sign
failure {
slackSend ...
}
// trigger every-works
always {
slackSend ...
}
}
}
它也会在每个stage
中使用。请参阅文档链接。