// // Sends Cloudwatch Event notifications to Slack // // // Setup: See setup in the readme file // const SLACK_URL = 'https://.slack.com/services/hooks/incoming-webhook'; // Replace const SLACK_CHANNEL_NAME = "#ops"; // Replace with yout own channel name const kmsEncyptedToken = 'Replace with your KMS token'; // Replace const SLACK_USERNAME = "webhookbot"; console.log('Loading function'); const AWS = require('aws-sdk'); const url = require('url'); const https = require('https'); const qs = require('querystring'); exports.handler = function(event, context) { var token = null; var slackReqOpts = null; if (token) { // Container reuse, simply process the event with the key in memory processEvent(event, context, slackReqOpts); } else { const encryptedBuf = new Buffer(kmsEncyptedToken, 'base64'); const cipherText = {CiphertextBlob: encryptedBuf}; const kms = new AWS.KMS(); kms.decrypt(cipherText, function (err, data) { if (err) { console.log("Decrypt error: " + err); context.fail(err); } else { token = data.Plaintext.toString('ascii'); const slackUrl = SLACK_URL; slackReqOpts = url.parse(slackUrl + '?token=' + token); slackReqOpts.method = 'POST'; slackReqOpts.headers = {'Content-Type': 'application/json'}; processEvent(event, context, slackReqOpts); } }); } }; var processEvent = function(event, context, slackReqOpts) { var source = event.source; var region = event.region; var detail = event.detail; var instanceId = detail['instance-id']; var state = detail.state; var text = []; text.push(source); text.push(' (' + region + ')'); text.push(': '); text.push(instanceId); text.push(' is '); text.push(state); var req = https.request(slackReqOpts, function (res) { if (res.statusCode === 200) { context.succeed('posted to slack'); } else { context.fail('status code: ' + res.statusCode); } }); req.on('error', function(e) { console.log('problem with request: ' + e.message); context.fail(e.message); }); req.write(JSON.stringify({ channel: SLACK_CHANNEL_NAME, username: SLACK_USERNAME, text: text.join(''), icon_emoji: ":ghost:" })); req.end(); }