I have created a SNS topic a cloud watch event (to trigger alerts on any instance state change) & a lambda function to send notification to 3rd party apps when any such event is triggered.
Below is my Lambda code -:
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 message = event.Records[0].Sns.Message;
var postData = {
"text": message
};
var options = {
method: 'POST',
hostname: 'hooks.slack.com',
port: 443,
path: process.env.CHAT_API_PATH
};
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();
};
The above code triggers a notification message on 3rd party app (Say on Slack channel) successfully and displays the message as below whenever any instance state is changed -:
{"version":"0","id":"c15cd3c9-d0aa-ca2e-71bb-c9b892c562c7","detail-type":"EC2 Instance State-change Notification","source":"aws.ec2","account":"288468818145","time":"2021-07-14T07:05:31Z","region":"us-east-1","resources":["arn:aws:ec2:us-east-1:288468818145:instance/i-0a3305ab8922ad61a"],"detail":{"instance-id":"i-0a3305ab8922ad61a","state":"stopping"}}
The only problem is, i want to display only "instance-id" and "state" of my instances in notification message and want my lambda to pass only these values how to do it ?
P.S. -: I don't want to touch SNS within cloudwatch target i.e. via "Input Transformer" to format my message instead want to handle it purely from Lambda.
message/ theevent. Parse / interpret the json and only use the"detail"info. - luk2302