var http = require('https'); var querystring = require('querystring'); // set the post request options var reqOptions = { hostname: 'hooks.slack.com', 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) { return; } 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 = []; Object.keys(d).forEach(function(k){ if(excludeKeys.indexOf(k) != -1) { return; } 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.setEncoding("utf8"); res.on('data', function(d) { console.log(d); // Wait for a response before calling succeed, otherwise // our Lambda function will exit too early context.succeed(); }); }); req.on('error', function(err){ console.log(err.message); // If we get an error, stop execution. context.fail(err.message); }); // Set request headers req.setHeader('Content-Type', 'application/x-www-form-urlencoded'); req.setHeader('Content-Length', payload.length); // Write the actual POST data req.write(payload); // Indicate no additional data will be written req.end(); };