Gửi thông báo từ Jenkins đến Slack thông qua Incoming Webhooks
Bài viết chia sẻ cách viết con bot gửi thông báo đến Slack từ Jenkins thông qua Incoming Webhooks.
Incoming Webhooks như một trạm trung gian đễ giúp chuyển thông tin từ Jenkins đến Slack.
1| Kết nối Slack vs Incoming Webhooks
Vào https://api.slack.com/messaging/webhooks rồi theo hướng dẫn để kết nối Incoming Webhooks với app của bạn bên Slack.
Sau khi kết nối xong, Webhook sẽ trả về cho bạn một URL có thông tin token. Giống như vầy:
https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX
Trong đó:
- url: https://hooks.slack.com/services/
- token: T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX
2| Viết file Jenkinsfile
#!/usr/bin/env groovy
import groovy.json.JsonOutput
@NonCPS
def _sendNotifySlack(text, color) {
def slackURL = 'https://hooks.slack.com/services/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'
def jenkinsIcon = 'https://wiki.jenkins-ci.org/download/attachments/2916393/logo.png'
def slackNotificationChannel = 'test_build_jenkins'
def slackBotName = 'Jenkins-build'
def payload = """
{
"attachments":[{
"title": "Job: ${env.JOB_NAME}",
"text":"${text}",
"color":"${color}"
}],
"channel":"${slackNotificationChannel}",
"username":"${slackBotName}",
"icon_url":"${jenkinsIcon}"
}
"""
sh "curl -X POST --data-urlencode \'payload=${payload}\' ${slackURL}"
}
@NonCPS
def notifySlack(String buildResult){
# def hasSummaryMatch = (buildResult =~ /\b(\w*(SUCCESS)\w*)\b/)
if ( buildResult == "SUCCESS" ) {
_sendNotifySlack("Job: ${env.JOB_NAME} with buildnumber ${env.BUILD_NUMBER} was successful", "good")
}
else if( buildResult == "FAILURE" ) {
_sendNotifySlack("Job: ${env.JOB_NAME} with buildnumber ${env.BUILD_NUMBER} was failed", "danger")
}
else if( buildResult == "UNSTABLE" ) {
_sendNotifySlack("Job: ${env.JOB_NAME} with buildnumber ${env.BUILD_NUMBER} was unstable", "warning")
}
else {
_sendNotifySlack("Job: ${env.JOB_NAME} with buildnumber ${env.BUILD_NUMBER} was unclear", "danger")
}
}
pipeline {
stages {
stage('Build Node Modules') {
steps {
echo "Build Original Image"
script {
docker.image('qmu1/webpack:latest').inside("-v $WORKSPACE:/workspace") { c ->
sh 'cd src/front; \
rm -rf node_modules; \
npm install; \
npm rebuild node-sass; \
npm install;'
}
}
}
}
}
post {
always {
notifySlack(currentBuild.currentResult)
}
}
}
Sau khi build xong, Jenkins sẽ gửi một thông báo đến slack như hình bên dưới: