Create a Slack notification using CloudWatch Alarms and AWS Lambda

Trigger a Cloudwatch alarm to invoke a Lambda function written in Go that calls the Slack API to post a message to your channel

Mohamed Labouardy
A Cloud Guru
3 min readApr 16, 2018

--

ChatOps has emerged as one of the most effective techniques to implement DevOps. Hence, it will be great to receive notifications and infrastructure alerts into collaboration messaging platforms like Slack & HipChat.

AWS CloudWatch Alarms and SNS are a great mix to build a real-time notification system as SNS supports multiple endpoints — including Email, HTTP, Lambda, SQS. Unfortunately SNS doesn’t support out of the box notifications to tools like Slack.

CloudWatch will trigger an alarm to send a message to an SNS topic if the monitoring data gets out of range. A Lambda function will be invoked in response of SNS receiving the message and will call the Slack API to post a message to Slack channel.

To get started, create an EC2 instance using the AWS Management Console or the AWS CLI:

Next, create a SNS topic:

Then, setup a CloudWatch alarm when the instance CPU utilization is higher than 40% and send notification to the SNS topic:

As a result:

To be able to post messages to slack channel, we need to create a Slack Incoming WebHook. Start by setting up an incoming webhook integration in your Slack workspace:

Note down the returned WebHook URL for upcoming part.

The Lambda handler function is written in Go, it takes as an argument the SNS message. Then, it parses it and queries the Slack API to post a message to the Slack channel configured in the previous section:

As Go is a compiled language, build the application and create a Lambda deployment package using the bash script below:

Once created, use the AWS CLI to deploy the function to Lambda. Make sure to override the Slack WebHook with your own:

Note: For non Gophers you can download the zip file directly from here.

From here, configure the invoking service for your function to be the SNS topic we created earlier:

Lambda Dashboard:

Let’s test it out, connect to your instance via SSH, then install stress which is a tool to do workload testing:

sudo yum install -y stress

Issue the following command to generate some workloads on the CPU:

stress — cpu 2 — timeout 60s

You should receive a Slack notification as below:

Now you can go even further and customize your Slack message!

Drop your comments, feedback, or suggestions below — or connect with me directly on Twitter @mlabouardy.

--

--

Mohamed Labouardy
A Cloud Guru

CTO & Co-Founder @Tailwarden — Maker of @Komiser.io and Author — Newsletter: https://devopsbulletin.com