In today's blog post, we're going to dive into how you can trigger a Lambda function using CloudWatch Alarms. As it stands now, you can't set this up directly. We'll walk through the process of using SNS topics to make this happen. Before we dive in, let's recap what CloudWatch Alarms, SNS topic and Lambda are.
CloudWatch Alarms are a feature within AWS that lets you monitor AWS resources and applications in real-time. They can alert you when something changes, like an increase in load on your server or a drop in performance. You set the conditions, and when these conditions are met, the alarm triggers. It's like having a watchman for your AWS environment, always ready to notify you when things aren't as expected.
AWS Lambda is a serverless computing service. It runs your code in response to events, like changes in data or user actions, without requiring you to manage servers. You provide the code and set the conditions under which it should run. Lambda takes care of the rest – from executing the code to scaling it as needed. It's a flexible, efficient way to run applications without the overhead of constant server management.
SNS (Simple Notification Service)
AWS SNS is a messaging service that facilitates communication between different services and applications. It allows you to send notifications or messages to a large number of recipients. You can use SNS to trigger emails, SMS messages, or even to communicate with other AWS services.
Example - Trigger Lambda from CloudWatch Alarms (via SNS)
Next up, let's dive into a practical example. I'm going to show you how to set up an alarm that triggers a Lambda function via an SNS topic. Here's our plan.
- Setting Up an EC2 Instance - We'll start by spinning up an EC2 instance. In our case, this instance typically has a CPU load under 5% when idle.
- Creating a CloudWatch Alarm - Our goal is to have an alarm that fires when the CPU usage hits 8%. This is just to demonstrate the process, so we're setting the threshold intentionally low.
- SNS Topic - Once our alarm triggers, it will send a notification to an SNS topic. This is our communication link between the alarm and the Lambda function.
- Lambda Function and SNS Integration - We'll use a Lambda function subscribed to our SNS topic. When messages arrive at the SNS topic, our Lambda function kicks into action.
Don't worry if this sounds complex now. It'll all make sense as we walk through each step of the example.
First, let's create an SNS topic which is just as easy as navigating to Amazon SNS > Topics and creating a new one.
In the next step, we will add this SNS topic as an action to the CloudWatch Alarm.
Create the CloudWatch Alarm
In this section, we'll create our CloudWatch Alarm. Assuming you've got your EC2 instance ready, you'll go to CloudWatch, then to 'All Alarms,' and set up a new one like this.
- Graph - The graph shows the CPU utilization percentage of your EC2 instance over time. The blue line represents the actual usage, and the dotted red line is the threshold we've set for the alarm.
- Namespace & Metric Name - We're monitoring the
CPUUtilizationmetric in the
- Statistic - We've chosen 'Average' as the statistic. This means the alarm will look at the average CPU utilization over a specified period.
- Period - The period is set to '1 minute,' indicating that the CPU utilization is averaged out and checked every minute.
- Conditions - We've selected a 'Static' threshold type, which uses a constant value as the trigger for the alarm.
- Threshold Condition - The condition is set to 'Greater/Equal', meaning the alarm will trigger when the CPU usage is greater than or equal to the threshold.
- Threshold Value - We've defined the threshold value as '8', which means the alarm will go off if the CPU utilization hits 8% or more.
Now that we've created the Alarm, we can add the SNS topic as an action under 'Configure actions' section of an alarm setup.
- Alarm State Trigger - The option 'In alarm' is selected, meaning that the action you're setting up will take place when the alarm's state is 'In alarm.' This state occurs when the metric being monitored by your alarm goes beyond the threshold you've set.
- Notification - The section below 'Alarm state trigger' allows you to define what happens when the alarm state is triggered. We've chosen 'Select an existing SNS topic' which means you're going to use an SNS topic you've already created.
- SNS Topic - The field 'Send a notification to...' is populated with
sns_test, which is the SNS topic we've created. When the alarm goes off, this SNS topic will receive a notification.
By configuring this action, you're ensuring that once the CloudWatch Alarm is triggered — in this case, when the CPU utilization of your EC2 instance exceeds the set threshold — a message will be sent to the
sns_test SNS topic. This SNS topic is then responsible for notifying subscribers, which can include our Lambda function, about the alarm. This setup creates a responsive monitoring system that can automatically initiate actions (like triggering a Lambda function) when specific conditions are met.
Now, let's set up the Lambda function. Here's a simple Python script we'll use. For the sake of keeping things straightforward, all it does is print out a message confirming that the Lambda function has been invoked, and it displays the message that the SNS topic sends to Lambda:
With this script, when the Lambda function is triggered, we'll see 'My Lambda Works' in the logs, followed by the event information that triggered it, which is sent from the SNS topic.
After creating the Lambda function with this script, the next step is to link it to our SNS topic. To do this, we go back to the SNS console, select our topic (
sns_test), and add the Lambda function as a subscriber. By doing so, whenever our CloudWatch Alarm triggers the SNS topic, it will in turn invoke our Lambda function with the details of the event.
It looks like the EC2 instance was barely breaking a sweat, not even hitting the 5% CPU usage mark, so I've tweaked the threshold down to 2%—yes, I can be a bit impatient sometimes!
And would you look at that, the alarm has now shifted into the 'Alarm State.'
What happens next is a neat cascade of events, the alarm notifies the SNS topic, and the SNS topic, in turn, triggers the Lambda function we've set up. Here is the output of the Lambda function which prints out the two messages.
That's all for this example. Remember, this is just a starting point—you can customize this setup to fit your needs. If it all makes sense, great! If you've got questions, just drop them in the comments.