1. Create a Topic on SNS
To set up Amazon SNS notifications
- Open the Amazon SNS console at https://eu-central-1.console.aws.amazon.com/sns/v3/home
- Choose Topics > Create
topic - Create a topic with Name: CheckHealthW3Server and Display name: Health WWW servers. Other things should be
default . - After that go to view detail of CheckHealthW3Server to create a subscription.
2. Create a subscription
We can ignore this step if we didn’t create a lambda function before.
- Click Create subscription
- Topic ARN: Enter a ARN of the CheckHealthW3Server topic.
- Protocol: select AWS Lambda
- Endpoint: An AWS Lambda function that can receive notifications from Amazon SNS
- That’s all for a subscription. We can create many subscriptions with other protocol.
3. Create a channel and config to get message from lambda function
- Slack > Create channel: #sns-notifications
- Create
a apps to post messages from external sources into Slack. Visit the link: https://channel.slack.com/apps and search app name: Incoming WebHooks - At
homepage the app choose Add configuration and choose Post to Channel is #sns-notifications - After that you can get value for Webhook URL like that: https://hooks.slack.com/services/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
4. Create a lambda function to be trigger by SNS service
- AWS Lambda > Create function
- We have three ways to create a function lambda. But we should use a blueprint because it helps us to assign this function to the topic we want automatically. At search field we use the keyword is sns-message and choose language is Nodejs.
- Fill these information for this function:
- Function name: notificationToSlack
- Execution role: Create a new role with basic Lambda permissions
- SNS topic: search CheckHealthW3Server
- Tick to Enable trigger
- Lambda function code: In this code you have to config again the path for calling webhook slack.
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 = {
"text": "*" + event.Records[0].Sns.Subject + "*"
};
var message = event.Records[0].Sns.Message;
var severity = "danger";
postData.attachments = [
{
"color": severity,
"text": message
}
];
var options = {
method: 'POST',
hostname: 'hooks.slack.com',
port: 443,
path: '/services/T2KFETZAQ/BH9KNUKU4/QOfFx4h08TF3D1OVKnhCmRS1'
};
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();
};
5. Publish a message to test
At the detail of the CheckHealthW3Server page.
- Click on Publish message
- Enter: Subject and Message body to send to the endpoint
- Open the #sns-notifications channel to see the result.