1. Introduction
In today’s cloud-native world, visibility into your system’s health is non-negotiable. You can’t fix what you can’t see — and that’s where AWS CloudWatch steps in. Even better? You can deploy powerful monitoring infrastructure in minutes using Terraform.
In this post, I’ll walk you through how to create:
- A custom CloudWatch metric
- A CloudWatch alarm that triggers when the metric crosses a threshold
- An SNS topic for alert notifications
All with infrastructure-as-code, following the same Terraform approach I used in this post.
2. Use case
Let’s say you want to monitor API latency. You’ll:
- Send custom latency values to CloudWatch from your app
- Set up a threshold (e.g., > 500ms)
- Trigger an alarm via SNS (email or automation)
3. Terraform Project Structure
Here’s a simple file layout:
cloudwatch-monitoring/
├── main.tf
├── variables.tf
├── outputs.tf
├── publish-metric.py # Optional - for testing
Step 1: Create an SNS Topic for Notifications
resource "aws_sns_topic" "alerts" {
name = "cloudwatch-alerts-topic"
}
resource "aws_sns_topic_subscription" "email_alert" {
topic_arn = aws_sns_topic.alerts.arn
protocol = "email"
endpoint = var.alert_email # e.g., "you@example.com"
}
Step 2: Create a CloudWatch Metric Alarm
resource "aws_cloudwatch_metric_alarm" "api_latency_alarm" {
alarm_name = "High-APILatency"
comparison_operator = "GreaterThanThreshold"
evaluation_periods = 3
metric_name = "APILatency"
namespace = "MyApp/Performance"
period = 60
statistic = "Average"
threshold = 500
alarm_description = "API latency is too high!"
actions_enabled = true
alarm_actions = [aws_sns_topic.alerts.arn]
dimensions = {
Endpoint = "/checkout"
}
}
Step 3: (Optional) Publish Custom Metrics with Python
import boto3
import time
cloudwatch = boto3.client('cloudwatch')
cloudwatch.put_metric_data(
Namespace='MyApp/Performance',
MetricData=[
{
'MetricName': 'APILatency',
'Dimensions': [{'Name': 'Endpoint', 'Value': '/checkout'}],
'Timestamp': time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
'Value': 600,
'Unit': 'Milliseconds'
},
]
)
print("Metric published!")
variables.tf
variable "alert_email" {
description = "Email address for CloudWatch alarm notifications"
type = string
}
Deploy with Terraform
terraform init
terraform apply -var="alert_email=your@email.com"
Done! Now You Can:
- Automatically track API latency (or any other custom metric)
- Get real-time alerts when something goes wrong
- Manage everything with version-controlled infrastructure code
4. Conclustion
Monitoring is more than just collecting data — it’s about getting actionable alerts before your users complain. By combining CloudWatch, SNS, and Terraform, you get a scalable, repeatable way to keep your system healthy.