Instantly share code, notes, and snippets.

Embed
What would you like to do?
AWS Lambda function to Slack Channel hookup
var https = require('https');
var util = require('util');
exports.handler = function(event, context) {
console.log(JSON.stringify(event, null, 2));
console.log('From SNS:', event.Records[0].Sns.Message);
var postData = {
"channel": "#aws-sns",
"username": "AWS SNS via Lamda :: DevQa Cloud",
"text": "*" + event.Records[0].Sns.Subject + "*",
"icon_emoji": ":aws:"
};
var message = event.Records[0].Sns.Message;
var severity = "good";
var dangerMessages = [
" but with errors",
" to RED",
"During an aborted deployment",
"Failed to deploy application",
"Failed to deploy configuration",
"has a dependent object",
"is not authorized to perform",
"Pending to Degraded",
"Stack deletion failed",
"Unsuccessful command execution",
"You do not have permission",
"Your quota allows for 0 more running instance"];
var warningMessages = [
" aborted operation.",
" to YELLOW",
"Adding instance ",
"Degraded to Info",
"Deleting SNS topic",
"is currently running under desired capacity",
"Ok to Info",
"Ok to Warning",
"Pending Initialization",
"Removed instance ",
"Rollback of environment"
];
for(var dangerMessagesItem in dangerMessages) {
if (message.indexOf(dangerMessages[dangerMessagesItem]) != -1) {
severity = "danger";
break;
}
}
// Only check for warning messages if necessary
if (severity == "good") {
for(var warningMessagesItem in warningMessages) {
if (message.indexOf(warningMessages[warningMessagesItem]) != -1) {
severity = "warning";
break;
}
}
}
postData.attachments = [
{
"color": severity,
"text": message
}
];
var options = {
method: 'POST',
hostname: 'hooks.slack.com',
port: 443,
path: '/services/your-slack-webhook-url-info-goes-here'
};
var req = https.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
context.done(null);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.write(util.format("%j", postData));
req.end();
};
@airdrummingfool

This comment has been minimized.

Show comment
Hide comment
@airdrummingfool

airdrummingfool Apr 27, 2016

Thanks for this! Your newest revision removed all definitions of color, which causes the dreaded "Process exited before completing request" error.

EDIT: Actually it looks like you renamed to severity. So if you change line 65's color to severity, all is good!

airdrummingfool commented Apr 27, 2016

Thanks for this! Your newest revision removed all definitions of color, which causes the dreaded "Process exited before completing request" error.

EDIT: Actually it looks like you renamed to severity. So if you change line 65's color to severity, all is good!

@davesade

This comment has been minimized.

Show comment
Hide comment
@davesade

davesade May 13, 2016

Hello and thank you for this. I confirm, that line 65 was causing troubles. Replace color with severity and it should be OK.

davesade commented May 13, 2016

Hello and thank you for this. I confirm, that line 65 was causing troubles. Replace color with severity and it should be OK.

@razgoren

This comment has been minimized.

Show comment
Hide comment
@razgoren

razgoren May 17, 2016

Great , after the change of line 65 it works

razgoren commented May 17, 2016

Great , after the change of line 65 it works

@terranware

This comment has been minimized.

Show comment
Hide comment
@terranware

terranware Jun 2, 2016

Sorry for the line 65 typo. Refactor oops! I wish there were Gist notifications. If you post a response to the Medium post I can address issues faster.

Owner

terranware commented Jun 2, 2016

Sorry for the line 65 typo. Refactor oops! I wish there were Gist notifications. If you post a response to the Medium post I can address issues faster.

@flynnCoolblue

This comment has been minimized.

Show comment
Hide comment
@flynnCoolblue

flynnCoolblue Jul 18, 2016

Anyone have any idea of how to get it to format nicely into Slack? just comes out as a huge blob of JSON that is hardly readable :(

flynnCoolblue commented Jul 18, 2016

Anyone have any idea of how to get it to format nicely into Slack? just comes out as a huge blob of JSON that is hardly readable :(

@faceleg

This comment has been minimized.

Show comment
Hide comment
@faceleg

faceleg Oct 10, 2016

I had to change the request portion to:

    var payload = 'payload=' + util.format('%j', postData);
    var options = {
        method: 'POST',
        hostname: 'hooks.slack.com',
        port: 443,
        path: '/services',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Content-Length': Buffer.byteLength(payload)
      }
    };

    var req = https.request(options, function(res) {
      res.setEncoding('utf8');
      res.on('data', function (chunk) {
        console.log(`BODY: ${chunk}`);
      });

      res.on('end', function () {
        context.done(null);
      });
    });

    req.on('error', function(e) {
      console.log('problem with request: ' + e.message);
    });    

    req.write(payload);

faceleg commented Oct 10, 2016

I had to change the request portion to:

    var payload = 'payload=' + util.format('%j', postData);
    var options = {
        method: 'POST',
        hostname: 'hooks.slack.com',
        port: 443,
        path: '/services',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Content-Length': Buffer.byteLength(payload)
      }
    };

    var req = https.request(options, function(res) {
      res.setEncoding('utf8');
      res.on('data', function (chunk) {
        console.log(`BODY: ${chunk}`);
      });

      res.on('end', function () {
        context.done(null);
      });
    });

    req.on('error', function(e) {
      console.log('problem with request: ' + e.message);
    });    

    req.write(payload);
@aayushKumarJarvis

This comment has been minimized.

Show comment
Hide comment
@aayushKumarJarvis

aayushKumarJarvis Oct 12, 2016

Can anyone please help me with this script as to how to do I alert particular owners (people) in a channel where messages are posted.

Thanks in advance

aayushKumarJarvis commented Oct 12, 2016

Can anyone please help me with this script as to how to do I alert particular owners (people) in a channel where messages are posted.

Thanks in advance

@jdrydn

This comment has been minimized.

Show comment
Hide comment
@jdrydn

jdrydn Nov 18, 2016

@aayushKumarJarvis You can modify line 11 (text: "...") and add @channel or @here, or specific usernames.

jdrydn commented Nov 18, 2016

@aayushKumarJarvis You can modify line 11 (text: "...") and add @channel or @here, or specific usernames.

@morugu

This comment has been minimized.

Show comment
Hide comment
@morugu

morugu Dec 16, 2016

customized this script.

  • Add reaction words from Elastic Beanstalk
  • Enable use mention

https://github.com/morugu/aws-lambda-function-templates/blob/master/sns/sns-to-slack.js

morugu commented Dec 16, 2016

customized this script.

  • Add reaction words from Elastic Beanstalk
  • Enable use mention

https://github.com/morugu/aws-lambda-function-templates/blob/master/sns/sns-to-slack.js

@makaivelli

This comment has been minimized.

Show comment
Hide comment
@makaivelli

makaivelli Mar 1, 2018

I guess the "message" value has changed from formatted text to json-like string recently.
I had to format the message to get human-readable text in slack:

function toText(obj) {
     var formatted = '';
     Object.keys(obj).forEach(function(key) {
       formatted += key + ': ' + obj[key] + '\n\n'
     });
     return formatted;
}

var message = event.Records[0].Sns.Message;
var messageObj = JSON.parse(message);
var message = toText(messageObj);

makaivelli commented Mar 1, 2018

I guess the "message" value has changed from formatted text to json-like string recently.
I had to format the message to get human-readable text in slack:

function toText(obj) {
     var formatted = '';
     Object.keys(obj).forEach(function(key) {
       formatted += key + ': ' + obj[key] + '\n\n'
     });
     return formatted;
}

var message = event.Records[0].Sns.Message;
var messageObj = JSON.parse(message);
var message = toText(messageObj);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment