Skip to content

Instantly share code, notes, and snippets.

Forked from turret-io/slackNotify.js
Last active November 1, 2018 18:41
Show Gist options
  • Save delemach/845a1a6dedf1c0a8cfd5 to your computer and use it in GitHub Desktop.
Save delemach/845a1a6dedf1c0a8cfd5 to your computer and use it in GitHub Desktop.
Parse SNS notification from Elastic Beanstalk and publish to Slack channel
var http = require('https');
var querystring = require('querystring');
// set the post request options
var reqOptions = {
hostname: '',
port: 443,
path: '/services/YOUR/SLACK/HOOK_HERE',
method: 'POST'
Parse the SNS payload. This function assumes only one message
notification is sent as part of the payload. The payload is
broken up into key:value pairs and returned as an object.
parse = function(payload) {
parts = payload.Records[0].Sns.Message.split('\n');
data = {};
parts.forEach(function(part) {
if(part.length < 1) {
key = part.split(':', 1)[0];
value = part.split(key+': ').reverse()[0];
data[key] = value;
return data;
Adds extra "attachment" data to display a customized message in Slack
instead of a simple message. We're excluding 'Message' here beacuse
we're using message as the main content of the Slack notification.
makeSlackAttachmentFields = function(d) {
var excludeKeys = ['RequestId', 'NotificationProcessId', 'Message'];
var arr = [];
if(excludeKeys.indexOf(k) != -1) {
arr.push({"title": k, "value": d[k], "short":false});
return arr;
Main Lambda handler
exports.handler = function(event, context) {
// Slack channel to notify
var channel = "#awseb";
// Parse event data from SNS
var data = parse(event);
// Create Slack attachment data
var dataFields = makeSlackAttachmentFields(data);
var postData = {
// Set the Slack channel within the payload
"channel": channel,
// Name of the Slack "bot" (this can be anything, doesn't
// have to be an existing user)
"username": "awsbot",
"attachments": [
"fallback": data.Message,
"text": data.Message,
"fields": dataFields
var payload = 'payload=' + querystring.escape(JSON.stringify(postData));
// Create HTTP request
var req = http.request(reqOptions, function(res){
res.on('data', function(d) {
// Wait for a response before calling succeed, otherwise
// our Lambda function will exit too early
req.on('error', function(err){
// If we get an error, stop execution.;
// Set request headers
req.setHeader('Content-Type', 'application/x-www-form-urlencoded');
req.setHeader('Content-Length', payload.length);
// Write the actual POST data
// Indicate no additional data will be written
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment