Created
October 19, 2022 12:15
-
-
Save r4rohan/47633008ecf5ae1bb41208aa842e09c5 to your computer and use it in GitHub Desktop.
Nodejs code to send Google Cloud Build status message to Slack Channel.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { IncomingWebhook } = require('@slack/webhook'); | |
const url = '[ENTER_YOUR_SLACK_TOKEN]'; | |
const webhook = new IncomingWebhook(url); | |
// subscribeSlack is the main function called by Cloud Functions. | |
module.exports.subscribeSlack = (pubSubEvent, context) => { | |
const build = eventToBuild(pubSubEvent.data); | |
const status = ['SUCCESS', 'FAILURE', 'INTERNAL_ERROR', 'TIMEOUT', 'CANCELLED']; | |
if (status.indexOf(build.status) === -1) { | |
return; | |
} | |
// Send message to Slack. | |
const message = createSlackMessage(build); | |
webhook.send(message); | |
}; | |
const eventToBuild = (data) => { | |
return JSON.parse(Buffer.from(data, 'base64').toString()); | |
} | |
const DEFAULT_COLOR = '#4285F4'; // blue | |
const STATUS_COLOR = { | |
SUCCESS: '#34A853', // green | |
FAILURE: '#EA4335', // red | |
TIMEOUT: '#FBBC05', // yellow | |
INTERNAL_ERROR: '#EA4335', // red | |
CANCELLED: '#808080' // grey | |
}; | |
const createSlackMessage = (build) => { | |
const message = { | |
attachments: [ | |
{ | |
color: STATUS_COLOR[build.status] || DEFAULT_COLOR, | |
blocks: [ | |
{ | |
type: "section", | |
text: { | |
type: "mrkdwn", | |
text: `*Cloud Build* - ${build.substitutions.TRIGGER_NAME}`, | |
}, | |
}, | |
{ | |
"type": "divider" | |
}, | |
{ | |
"type": "section", | |
"fields": [ | |
{ | |
"type": "mrkdwn", | |
"text": `*Github Repo:*\n${build.substitutions.REPO_NAME}`, | |
}, | |
{ | |
"type": "mrkdwn", | |
"text": `*Branch:*\n${build.substitutions.BRANCH_NAME}`, | |
}, | |
{ | |
"type": "mrkdwn", | |
"text": `*Build Status:*\n${build.status}`, | |
}, | |
{ | |
"type": "mrkdwn", | |
"text": `*Build Logs:*\n<${build.logUrl}|Log URL>`, | |
} | |
] | |
}, | |
{ | |
"type": "divider" | |
}, | |
], | |
}, | |
], | |
}; | |
return message; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "google-container-slack", | |
"version": "0.0.1", | |
"description": "Slack integration for Google Cloud Build, using Google Cloud Functions", | |
"main": "index.js", | |
"dependencies": { | |
"@slack/bolt": "3.12.1", | |
"@slack/webhook": "6.0.0", | |
"@google-cloud/pubsub": "^0.18.0" | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment