Last active
February 9, 2022 09:19
-
-
Save vgeshel/1dba698aed9e8b39a464 to your computer and use it in GitHub Desktop.
AWS Lambda function for forwarding SNS notifications to Slack
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
console.log('Loading function'); | |
const https = require('https'); | |
const url = require('url'); | |
// to get the slack hook url, go into slack admin and create a new "Incoming Webhook" integration | |
const slack_url = 'https://hooks.slack.com/services/...'; | |
const slack_req_opts = url.parse(slack_url); | |
slack_req_opts.method = 'POST'; | |
slack_req_opts.headers = {'Content-Type': 'application/json'}; | |
exports.handler = function(event, context) { | |
(event.Records || []).forEach(function (rec) { | |
if (rec.Sns) { | |
var req = https.request(slack_req_opts, 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({text: JSON.stringify(rec.Sns.Message, null, ' ')})); // for testing: , channel: '@vadim' | |
req.end(); | |
} | |
}); | |
}; |
How to add 2 slack urls?
How do I update "rec.Sns.Message" to be some custom text? Can I set "rec.Sns.Message" from somewhere in the AWS dashboard?
Newbie here - Can someone explain in little more detail on how to add this into a Lambda? I created a Lambda function, chose its runtime to be Nodejs 10.x and it opens with a default file of index.js. I assume I can not copy and paste this code into the index.js? Anything else special needed to call this from SNS?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Works! Just what I needed, thank you! 😄