How do I create an AWS CloudWatch Metric Alarm?
Overview
In this guide, we will demonstrate how to set up an AWS CloudWatch Metric Alarm to monitor an EC2 instance. CloudWatch Alarms allow you to watch specific metrics and react accordingly when thresholds are breached. This is useful for maintaining and monitoring system health.
What We Will Do
- Provision an EC2 instance.
- Set up a CloudWatch Metric to monitor CPU utilization.
- Create a CloudWatch Metric Alarm that triggers when the CPU utilization exceeds a specified threshold.
The Code
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
// Create an EC2 instance
const example = new aws.ec2.Instance("example", {
ami: "ami-0c55b159cbfafe1f0",
instanceType: aws.ec2.InstanceType.T2_Micro,
tags: {
Name: "PulumiExampleInstance",
},
});
// Create an SNS topic to notify when the alarm triggers
const exampleTopic = new aws.sns.Topic("example", {name: "example-topic"});
// Create a CloudWatch Metric Alarm
const cpuTooHigh = new aws.cloudwatch.MetricAlarm("cpu_too_high", {
name: "EC2_CPU_Too_High",
comparisonOperator: "GreaterThanThreshold",
evaluationPeriods: 2,
metricName: "CPUUtilization",
namespace: "AWS/EC2",
period: 120,
statistic: "Average",
threshold: 80,
alarmDescription: "This metric monitors EC2 CPU utilization",
dimensions: {
InstanceId: example.id,
},
alarmActions: [exampleTopic.arn],
});
export const instanceId = example.id;
export const alarmName = cpuTooHigh.name;
export const snsTopicArn = exampleTopic.arn;
Key Points
- Provider Configuration: Specifies the AWS region.
- EC2 Instance: An instance of type
t2.micro
is created for demonstration. - CloudWatch Metric Alarm: Monitors the
CPUUtilization
of the EC2 instance, triggering an alarm when it exceeds 80% for 2 consecutive periods. - SNS Topic: Notifies you when the alarm goes off.
Conclusion
You’ve learned how to provision an EC2 instance and set up a CloudWatch metric alarm to monitor its CPU utilization. This ensures you are alerted when the instance experiences high CPU load, allowing for proactive infrastructure management.
Deploy this code
Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.
Sign upNew to Pulumi?
Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.
Sign upThank you for your feedback!
If you have a question about how to use Pulumi, reach out in Community Slack.
Open an issue on GitHub to report a problem or suggest an improvement.