Ravindra BagaleCourses & study guides मराठी

Chapter 13: Monitoring Basics

DevOps

13.10 CloudWatch in one paragraph (secondary path)

Why: the problem

Many Indian companies run fully on AWS: think of a startup like Meesho or a project at Wipro for a US bank. They often start with Amazon CloudWatch because it is already there. Every EC2, RDS database, load balancer and Lambda function sends metrics to CloudWatch without any setup. You can draw dashboards, create alarms that send email through SNS, and even stop or reboot an EC2 automatically. You do not run any monitoring server yourself. The catch: custom metrics and many alarms cost money, and the query language is weaker than PromQL. So many teams use both: CloudWatch for AWS services, Prometheus for apps and Kubernetes, and Grafana on top of both. That is why you must know CloudWatch too, not only Prometheus.

What we will build

You will do the three most common CloudWatch jobs with the AWS CLI. First, send a custom metric (orders per minute) with put-metric-data. Second, create an alarm on EC2 CPU and on an RDS free storage metric that emails you through SNS, and test it. Third, write the same alarm in Terraform so it is code. You will also see the cost rules so you do not get a surprise bill.

What: every term in plain English

  • Namespace — A group of metrics, like AWS/EC2, AWS/RDS or your own MyApp.
  • Dimension — A tag on a metric, like InstanceId=i-0abc... Same as a Prometheus label.
  • Period — The time bucket of a data point, like 60 or 300 seconds.
  • Statistic — How points are combined: Average, Sum, Maximum, Minimum, p95.
  • Alarm — Watches one metric and changes state: OK, ALARM or INSUFFICIENT_DATA.
  • SNS topic — A message channel. Alarms publish to it; it sends email, SMS or Lambda.
  • Evaluation periods — How many periods in a row must breach before ALARM.
  • Custom metric — A metric you send yourself. It costs a small fee each month.
Check who you are Set the region List EC2 metrics Create the SNS topic Create alarms Test an alarm
CloudWatch: metric to alarm to SNS to email

How: step by step

  1. Check who you are

    aws sts get-caller-identity
    

    What it does: Confirms the CLI is logged in.

    Output

    { "Account": "111122223333", "Arn": "arn:aws:iam::111122223333:user/ravi-lab" }
    
  2. Set the region

    export AWS_DEFAULT_REGION=ap-south-1
    

    What it does: Mumbai region for all commands.

    Output

    (no output)
    
  3. List EC2 metrics

    aws cloudwatch list-metrics --namespace AWS/EC2 --metric-name CPUUtilization --output text | head -3
    

    What it does: Shows which instances send CPU.

    Output

    METRICS CPUUtilization AWS/EC2
    DIMENSIONS InstanceId i-0abc1234def567890
    
  4. Create the SNS topic

    See Example 2
    

    What it does: Email channel for alarms.

    Output

    "TopicArn": "arn:aws:sns:ap-south-1:111122223333:ops-alerts"
    
  5. Create alarms

    See Example 2
    

    What it does: CPU and RDS storage alarms.

    Output

    (no output)
    
  6. Test an alarm

    aws cloudwatch set-alarm-state ... (see Verify)
    

    What it does: Forces ALARM so you see the email.

    Output

    (no output)
    

Example 1: Send a custom business metric with put-metric-data

Stack. AWS CLI, CloudWatch custom metrics, MySQL, cron

Goal. Send a custom business metric with put-metric-data.

push_orders.sh

#!/usr/bin/env bash
# Run every minute from cron. Counts orders in the last minute from MySQL.
COUNT=$(mysql -N -e "SELECT COUNT(*) FROM shop.orders WHERE created_at > NOW() - INTERVAL 1 MINUTE")
aws cloudwatch put-metric-data \
  --namespace "Shop/Orders" \
  --metric-name OrdersPerMinute \
  --dimensions Env=prod,City=Pune \
  --value "$COUNT" --unit Count
echo "$(date +%T) sent OrdersPerMinute=$COUNT"

crontab -e line

* * * * * /home/ec2-user/push_orders.sh >> /var/log/push_orders.log 2>&1

What each line does

  • mysql -N -e "..." — Runs a SQL query and prints only the number, no header.
  • --namespace "Shop/Orders" — Your own group. Do not start with AWS/.
  • --dimensions Env=prod,City=Pune — Tags to filter by. Each new combination is a new paid metric.
  • --value "$COUNT" --unit Count — The number and its unit.
  • * * * * * — cron runs it every minute.

Green output

$ bash push_orders.sh
21:30:00 sent OrdersPerMinute=42
$ aws cloudwatch get-metric-statistics --namespace Shop/Orders --metric-name OrdersPerMinute \
    --dimensions Name=Env,Value=prod Name=City,Value=Pune \
    --start-time $(date -u -d "-10 min" +%FT%TZ) --end-time $(date -u +%FT%TZ) \
    --period 60 --statistics Sum --query "Datapoints[].Sum" --output text
42.0  39.0  45.0

Expected result. Your business number is now in CloudWatch, next to EC2 CPU. You can graph it and alarm when orders drop to zero.

Example 2: Alarms on EC2 CPU and RDS free storage, with email through SNS

Stack. AWS CLI, CloudWatch alarms, SNS, RDS

Goal. Alarms on EC2 CPU and RDS free storage, with email through SNS.

Commands

TOPIC=$(aws sns create-topic --name ops-alerts --query TopicArn --output text)
aws sns subscribe --topic-arn "$TOPIC" --protocol email --notification-endpoint oncall@example.in

aws cloudwatch put-metric-alarm \
  --alarm-name orders-web-1-cpu-high \
  --namespace AWS/EC2 --metric-name CPUUtilization \
  --dimensions Name=InstanceId,Value=i-0abc1234def567890 \
  --statistic Average --period 300 --evaluation-periods 2 \
  --threshold 85 --comparison-operator GreaterThanThreshold \
  --alarm-actions "$TOPIC" --ok-actions "$TOPIC"

aws cloudwatch put-metric-alarm \
  --alarm-name orders-db-storage-low \
  --namespace AWS/RDS --metric-name FreeStorageSpace \
  --dimensions Name=DBInstanceIdentifier,Value=orders-db \
  --statistic Minimum --period 300 --evaluation-periods 1 \
  --threshold 5000000000 --comparison-operator LessThanThreshold \
  --alarm-actions "$TOPIC"

What each line does

  • sns create-topic — Makes the channel. Returns its ARN.
  • sns subscribe --protocol email — Sends a confirm email. Click the link once.
  • --period 300 --evaluation-periods 2 — Two 5-minute periods in a row: 10 minutes above 85%.
  • GreaterThanThreshold — Alarm when the value is above the threshold.
  • --ok-actions — Also email when it is back to normal.
  • FreeStorageSpace ... LessThanThreshold 5000000000 — Alarm when the RDS disk has less than 5 GB free.

Green output

{
    "TopicArn": "arn:aws:sns:ap-south-1:111122223333:ops-alerts"
}
{
    "SubscriptionArn": "pending confirmation"
}
$ aws cloudwatch describe-alarms --alarm-name-prefix orders --query "MetricAlarms[].[AlarmName,StateValue]" --output table
-----------------------------------------
|            DescribeAlarms             |
+--------------------------+------------+
|  orders-db-storage-low   |  OK        |
|  orders-web-1-cpu-high   |  OK        |
+--------------------------+------------+

Expected result. Two alarms are watching. When CPU stays above 85% for 10 minutes or the database disk drops under 5 GB, you get an email.

Example 3: The same CPU alarm as code with Terraform

Stack. Terraform, AWS provider

Goal. The same CPU alarm as code with Terraform.

alarms.tf

provider "aws" {
  region = "ap-south-1"
}

resource "aws_sns_topic" "ops" {
  name = "ops-alerts"
}

resource "aws_sns_topic_subscription" "oncall" {
  topic_arn = aws_sns_topic.ops.arn
  protocol  = "email"
  endpoint  = "oncall@example.in"
}

variable "web_instances" {
  default = ["i-0abc1234def567890", "i-0def5678abc123456"]
}

resource "aws_cloudwatch_metric_alarm" "cpu_high" {
  for_each            = toset(var.web_instances)
  alarm_name          = "cpu-high-${each.value}"
  namespace           = "AWS/EC2"
  metric_name         = "CPUUtilization"
  dimensions          = { InstanceId = each.value }
  statistic           = "Average"
  period              = 300
  evaluation_periods  = 2
  threshold           = 85
  comparison_operator = "GreaterThanThreshold"
  alarm_actions       = [aws_sns_topic.ops.arn]
  ok_actions          = [aws_sns_topic.ops.arn]
  treat_missing_data  = "breaching"
}

What each line does

  • aws_sns_topic — Creates the ops-alerts topic.
  • aws_sns_topic_subscription — Adds the email subscriber.
  • for_each = toset(var.web_instances) — One alarm per instance from one block.
  • dimensions = { InstanceId = each.value } — Which server this alarm watches.
  • treat_missing_data = "breaching" — No data (server stopped) also counts as a problem.

Green output

$ terraform init && terraform apply -auto-approve
aws_sns_topic.ops: Creation complete after 1s
aws_cloudwatch_metric_alarm.cpu_high["i-0abc1234def567890"]: Creation complete after 1s
aws_cloudwatch_metric_alarm.cpu_high["i-0def5678abc123456"]: Creation complete after 1s
Apply complete! Resources: 4 added, 0 changed, 0 destroyed.

Expected result. Alarms are now code. Add a server id to the list, run apply, and the new server gets the same alarm. Review changes in a pull request like any code.

Verify: did it work?

  1. Force the alarm to test email

    aws cloudwatch set-alarm-state --alarm-name orders-web-1-cpu-high --state-value ALARM --state-reason "test from lab"
    

    What it does: You should get an ALARM email in a minute.

    Output

    (no output; email: ALARM: "orders-web-1-cpu-high" in Asia Pacific (Mumbai))
    
  2. See alarm history

    aws cloudwatch describe-alarm-history --alarm-name orders-web-1-cpu-high --max-items 3 --query "AlarmHistoryItems[].HistorySummary"
    

    What it does: Shows state changes.

    Output

    [ "Alarm updated from OK to ALARM", "Alarm updated from ALARM to OK" ]
    

When it is red 1

No email arrives when the alarm fires

Cause. The email subscription was never confirmed.

Fix, step by step

  1. aws sns list-subscriptions-by-topic --topic-arn YOUR_TOPIC_ARN
  2. If it says PendingConfirmation, open the AWS email and click Confirm.
  3. Test again with set-alarm-state.

When it is red 2

Alarm stays in INSUFFICIENT_DATA

Cause. The metric name, namespace or dimension is wrong, so no data matches.

Fix, step by step

  1. Run aws cloudwatch list-metrics with the same namespace and name.
  2. Copy the exact dimension name and value.
  3. Update the alarm.

When it is red 3

An error occurred (InvalidParameterValue) ... namespace AWS/ reserved

Cause. Custom metrics cannot use a namespace starting with AWS/.

Fix, step by step

  1. Use your own name like Shop/Orders.
  2. Run put-metric-data again.

Cleanup

  1. Delete the lab alarms

    aws cloudwatch delete-alarms --alarm-names orders-web-1-cpu-high orders-db-storage-low
    

    What it does: Stops alarm charges.

    Output

    (no output)
    
  2. Remove Terraform resources

    terraform destroy -auto-approve
    

    What it does: Removes the topic and alarms made by Terraform.

    Output

    Destroy complete! Resources: 4 destroyed.
    

Ravindra Bagale's Tip

On AWS, CloudWatch is ready from day one. But custom metrics cost money — when the lab is done, delete the alarm.

Practice tasks

Easy CloudWatch dashboard

Why: A shared AWS dashboard helps managers too.

What to do: Make a CloudWatch dashboard with EC2 CPU and OrdersPerMinute.

How:
  1. CloudWatch, Dashboards, Create.
  2. Add two line widgets.

Check: One dashboard shows both.

Medium Alarm when orders drop to zero

Why: Zero orders at 8 p.m. means something is broken.

What to do: Alarm on OrdersPerMinute Sum below 1 for 5 minutes.

How:
  1. Use LessThanThreshold with threshold 1.
  2. treat_missing_data breaching.

Check: The alarm fires when you stop the cron script.

Hard Auto-recover an EC2

Why: AWS can recover a broken host by itself.

What to do: Add an alarm on StatusCheckFailed_System with the recover action.

How:
  1. Action arn:aws:automate:ap-south-1:ec2:recover.
  2. Period 60, evaluation 2.

Check: The alarm exists with the recover action.

Easy Say CloudWatch in two lines

Why: If you can say it simply, you understand it. Juniors and interviewers both want the short version first.

What to do: Write two short lines about CloudWatch for a fresher who knows only Linux, Git and Docker basics.

How:
  1. Write the problem it solves.
  2. Write the one command, query or config line you use for it.
  3. Read it aloud to a friend.

Check: A fresher understands it without asking a question.

Easy Keep a throwaway monitoring lab

Why: Practice needs a lab you can break. If it gets messy, you delete the containers and start again in one minute.

What to do: Run Node Exporter in Docker and read its metrics page.

How:
  1. docker run -d --name ne -p 9100:9100 prom/node-exporter
  2. curl -s localhost:9100/metrics | grep node_load1
  3. docker rm -f ne

Check: You see a line that starts with node_load1 and a number.

Medium Do it on a second stack

Why: Monitoring ideas must work on Prometheus and on CloudWatch. Only the tool changes, not the thinking.

What to do: Repeat this lesson on a different stack than the one you used first.

How:
  1. If you used Prometheus, try the CloudWatch console or AWS CLI.
  2. Keep the same question: is it up, is it fast, is it failing, is it full?
  3. Compare the two graphs side by side.

Check: Both tools answer the same question with a number and a graph.

Medium Break it on purpose

Why: You must know the red error by face. During an outage there is no time to read slowly.

What to do: Cause one error from the "When it is red" part of this lesson and fix it.

How:
  1. Follow the error section.
  2. Copy the exact message into your notes.
  3. Write the fix in one line.

Check: You fixed it using only the steps, without searching the web.

Medium Write a one-page runbook

Why: At 2 a.m. nobody remembers PromQL. A short page saves the on-call person.

What to do: Write a one-page runbook for this lesson.

How:
  1. Title, when the alert fires, the graph to open, the exact commands, how to check, how to undo.

Check: A teammate can follow it alone, without calling you.

Hard Explain it like an interview

Why: Interviewers want real stories, not definitions.

What to do: Record a 60 second answer about this lesson.

How:
  1. Say the problem, the metric you watched, the number you saw and the fix.

Check: Your answer has a real metric name and a real number.

Hard Draw the flow top to bottom

Why: A drawing shows where a number is born and where it ends up.

What to do: Draw this lesson as boxes from top to bottom.

How:
  1. Start at the server or app, go through the exporter, Prometheus or CloudWatch, then Grafana, then the alert on your phone.

Check: Each box matches a real command or file in this lesson.

Homework: try at home

Try at home

At home, on a free-tier EC2, create a CPU alarm at 60% for 5 minutes, run stress-ng --cpu 1 --timeout 600, and wait for the email. Then delete the alarm. Note the time between start of load and email.

Recap

  • CloudWatch collects AWS service metrics with no setup.
  • Send your own numbers with put-metric-data.
  • Alarms publish to SNS, which emails or calls Lambda.
  • Write alarms in Terraform so they are code.
  • Custom metrics and alarms cost money; delete lab ones.

FAQ

CloudWatch or Prometheus?

CloudWatch for AWS services, Prometheus for apps and Kubernetes. Many teams use both with Grafana.

How much does CloudWatch cost?

Basic EC2 metrics are free. Custom metrics, detailed monitoring, alarms and dashboards have small monthly fees per item.

Can CloudWatch alarm on logs?

Yes, with metric filters on CloudWatch Logs.

What is a composite alarm?

An alarm built from other alarms with AND and OR, to reduce noise.

Is there a managed Grafana on AWS?

Yes, Amazon Managed Grafana.

Interview questions

  1. How do you create a CloudWatch alarm for high CPU?

    put-metric-alarm on AWS/EC2 CPUUtilization with the InstanceId dimension, a period, evaluation periods, threshold and an SNS action; or the same in Terraform.

  2. How do you get memory metrics from EC2?

    Install the CloudWatch agent; EC2 does not report memory by itself.

  3. What is the difference between a metric, a dimension and a namespace?

    Namespace is the group, metric is the measurement, dimension is a key-value tag that identifies the resource.

  4. How do you publish a custom metric?

    PutMetricData API, the CLI, an SDK, the agent, or Embedded Metric Format in logs.

  5. How would you monitor RDS?

    CloudWatch alarms on CPUUtilization, FreeStorageSpace, DatabaseConnections, ReadLatency and WriteLatency, plus Performance Insights.

Quick quiz

Q1. Which AWS service sends the alarm email?

Amazon SNS.

Q2. What are the three alarm states?

OK, ALARM, INSUFFICIENT_DATA.

Q3. Can a custom namespace start with AWS/?

No.

Q4. What does evaluation-periods 2 with period 300 mean?

Ten minutes above the threshold before ALARM.

Q5. Why use Terraform for alarms?

Repeatable, reviewed and the same on every server.

Did you understand? Let us try it once more.

Ravi Sir's Cards for this lesson

मराठी cards