Skip to main content

Cloud and deployment · Beginner · 18 min

Create CloudWatch alarms that email you when something breaks

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · AWS CLI 2.42.4

You will have an SNS topic that emails you and three CloudWatch alarms, for high EC2 CPU, a failed system status check that recovers the instance and any Lambda error, each tested with a forced state change.

On this page

Most AWS accounts collect metrics nobody reads. EC2 reports CPU and health checks, Lambda counts every error, and all of it sits in CloudWatch until someone opens the console. An alarm turns one of those numbers into a message: when the metric crosses a line for long enough, CloudWatch changes the alarm's state and runs the actions you gave it, such as sending an email through Amazon SNS or recovering an instance.

In this tutorial you build a small alerting setup from the command line:

  • an SNS topic with your email address subscribed and confirmed;
  • an alarm when an EC2 instance's average CPU stays above 80% for 10 minutes;
  • an alarm when the instance fails its system status check, which also asks EC2 to recover it onto healthy hardware;
  • an alarm when a Lambda function reports even one error.

For each alarm you choose the period, how many periods must breach and what happens when no data arrives. Then you force every alarm into the ALARM state to prove the email path works, and read the alarm's history to see what happened.

Everything you create is named alarms-demo-..., and your working files live in ~/alarms-demo. Three standard alarms fit inside the CloudWatch free tier if you are not already using it up; the last step shows how to check, and removes everything.

Step 1 · Install the AWS CLI and confirm the account

Install curl, unzip and jq, then version 2.42.4 of the AWS CLI from Amazon's versioned installer. uname -m prints x86_64 or aarch64, which matches Amazon's file names:

Bash
sudo apt update
sudo apt install -y curl unzip jq ca-certificates
AWS_CLI_VERSION=2.42.4
cd "$(mktemp -d)"
curl -fsSLo awscliv2.zip "https://awscli.amazonaws.com/awscli-exe-linux-$(uname -m)-${AWS_CLI_VERSION}.zip"
unzip -q -o awscliv2.zip
sudo ./aws/install
aws --version

If the AWS CLI is already installed, the installer stops and says so; run sudo ./aws/install --update instead. The CLI does not get updates from apt, so to upgrade later you run the same commands with a newer version number. The zip is a large download, so on a prepaid mobile bundle fetch it once over Wi-Fi and keep it.

Point the CLI at your sandbox account. If you use a named profile, run export AWS_PROFILE=<your-sandbox-profile> first (replace the placeholder); /tutorials/set-up-the-aws-cli-with-sso-and-named-profiles shows how to set one up. Then check who you are:

Bash
aws sts get-caller-identity --query Account --output text

Check it worked

aws --version starts with aws-cli/2.42.4, and the second command prints the 12-digit ID of your sandbox account. If it prints a different account, stop and fix your profile before you create anything.

Step 2 · Write down what you are watching

Alarms point at one resource through a dimension, such as InstanceId for EC2 or FunctionName for Lambda. Put those values, your email address and the Region in a small alarms.env file, so every later command (and a new terminal) can load them with . ./alarms.env. Replace the three placeholder values with your own:

Bash
mkdir -p ~/alarms-demo
cd ~/alarms-demo
cat > alarms.env <<'EOF'
export AWS_REGION=eu-west-2
export ALERT_EMAIL=you@example.com
export INSTANCE_ID=i-0123456789abcdef0
export FUNCTION_NAME=hello-lambda
EOF

Use the Region your instance and function run in: an alarm can only watch metrics in its own Region. If you work from Africa and your resources are in Cape Town (af-south-1), use that; it is an opt-in Region, so it must be turned on for the account first. To find your instance ID and function names, list them:

Bash
aws ec2 describe-instances --query 'Reservations[].Instances[].[InstanceId, Tags[?Key==`Name`].Value | [0]]' --output text
aws lambda list-functions --query 'Functions[].FunctionName' --output text

Load the file and confirm both resources exist before you build alarms on them:

Bash
cd ~/alarms-demo
. ./alarms.env
aws ec2 describe-instances --instance-ids "$INSTANCE_ID" \
  --query 'Reservations[0].Instances[0].[InstanceId, InstanceType, State.Name]' --output text
aws lambda get-function --function-name "$FUNCTION_NAME" \
  --query 'Configuration.[FunctionName, Runtime]' --output text

Check it worked

The first command prints your instance ID, its type and running. The second prints your function name and its runtime. An InvalidInstanceID.NotFound or ResourceNotFoundException error means a typo in alarms.env or the wrong Region: CloudWatch accepts an alarm on a resource that does not exist, and it would never fire, so fix it now.

Step 3 · Create an SNS topic and confirm your email

CloudWatch does not send email itself. It publishes to an SNS topic, and SNS delivers to everyone subscribed. One topic for all your alarms keeps the list of people in one place. Create it and save its ARN to alarms.env:

Bash
cd ~/alarms-demo
. ./alarms.env
TOPIC_ARN=$(aws sns create-topic --name alarms-demo-alerts --query TopicArn --output text)
echo "export TOPIC_ARN=${TOPIC_ARN}" >> alarms.env
echo "$TOPIC_ARN"

Subscribe your address:

Bash
aws sns subscribe --topic-arn "$TOPIC_ARN" --protocol email \
  --notification-endpoint "$ALERT_EMAIL"

AWS answers with "SubscriptionArn": "pending confirmation" and sends a message from AWS Notifications to that address. Open it and choose Confirm subscription. Until you do, SNS delivers nothing to you, and every alarm you build is silent. If the email is not in your inbox after a few minutes, look in spam, and mark it as not spam so the alarms land in your inbox too.

List the subscriptions on the topic:

Bash
aws sns list-subscriptions-by-topic --topic-arn "$TOPIC_ARN" \
  --query 'Subscriptions[].[Protocol, Endpoint, SubscriptionArn]' --output text

Then send yourself a test message through the topic:

Bash
aws sns publish --topic-arn "$TOPIC_ARN" \
  --subject "alarms-demo: test" \
  --message "If you can read this, SNS can reach you."

Check it worked

Before you click the link, the last column of the subscription list says PendingConfirmation. After you click it, the same command shows a full subscription ARN ending in a long ID. A minute after publish, an email with the subject alarms-demo: test is in your inbox. Do not go on until it is: every later test depends on it.

Step 4 · Alarm on high CPU for 10 minutes

Three settings decide when an alarm fires:

  • Period is how many seconds each data point covers. EC2 basic monitoring, which is free, sends a CPU value every 5 minutes, so the shortest useful period here is 300. A shorter period needs detailed monitoring, which is billed per metric.
  • Evaluation periods is how many recent periods CloudWatch looks at, and datapoints to alarm is how many of those must breach. Two out of two 5-minute periods means 10 minutes in a row above the line. A single busy minute, such as a package update, does not wake you up.
  • Treat missing data says what a gap means. The default, missing, sends the alarm to INSUFFICIENT_DATA when there is no data at all, which is what you want for an instance: a stopped server is not "high CPU".

Create the alarm. --ok-actions sends a second email when CPU drops back, so you know the problem has passed:

Bash
cd ~/alarms-demo
. ./alarms.env
aws cloudwatch put-metric-alarm \
  --alarm-name alarms-demo-cpu-high \
  --alarm-description "CPU above 80% for 10 minutes on ${INSTANCE_ID}" \
  --namespace AWS/EC2 --metric-name CPUUtilization \
  --dimensions Name=InstanceId,Value="$INSTANCE_ID" \
  --statistic Average --period 300 \
  --evaluation-periods 2 --datapoints-to-alarm 2 \
  --threshold 80 --comparison-operator GreaterThanThreshold \
  --treat-missing-data missing \
  --alarm-actions "$TOPIC_ARN" --ok-actions "$TOPIC_ARN"

put-metric-alarm prints nothing when it works. Running it again with the same name replaces the alarm, so you can change a setting by editing the command and running it again.

Check it worked

Read the alarm back:

Bash
aws cloudwatch describe-alarms --alarm-names alarms-demo-cpu-high \
  --query 'MetricAlarms[0].[StateValue, Period, EvaluationPeriods, DatapointsToAlarm, Threshold, TreatMissingData]' \
  --output text

It prints the state followed by 300, 2, 2, 80.0 and missing. The state starts as INSUFFICIENT_DATA and turns OK within about ten minutes, once CloudWatch has two data points from a quiet instance.

Step 5 · Recover the instance when its host fails

EC2 runs two status checks every minute and reports them for free. StatusCheckFailed_Instance is about your operating system, such as a full disk or a broken network setting. StatusCheckFailed_System is about the AWS hardware and network underneath, which you cannot fix yourself. The metric is 0 while the check passes and 1 when it fails.

For a system failure, an alarm can do more than email you: the recover action asks EC2 to move the instance to healthy hardware. The instance keeps its ID, its private and public IP addresses and its EBS volumes, but it reboots, so anything held only in memory is lost, as is any instance store data. Recovery only works with this system check, never the instance check, and only on supported instance types with EBS storage; the AWS page on instance recovery lists them.

Most current instance types already get simplified automatic recovery by default. The alarm adds an email when it happens, and AWS says the action based recovery starts faster.

AWS recommends two evaluation periods of one minute for a recover alarm. The action's ARN names the Region:

Bash
cd ~/alarms-demo
. ./alarms.env
aws cloudwatch put-metric-alarm \
  --alarm-name alarms-demo-system-check-recover \
  --alarm-description "System status check failed on ${INSTANCE_ID}; recovering" \
  --namespace AWS/EC2 --metric-name StatusCheckFailed_System \
  --dimensions Name=InstanceId,Value="$INSTANCE_ID" \
  --statistic Maximum --period 60 \
  --evaluation-periods 2 --datapoints-to-alarm 2 \
  --threshold 0 --comparison-operator GreaterThanThreshold \
  --treat-missing-data missing \
  --alarm-actions "arn:aws:automate:${AWS_REGION}:ec2:recover" "$TOPIC_ARN" \
  --ok-actions "$TOPIC_ARN"

Maximum over one minute is 1 if the check failed at any moment in it, and the threshold "greater than 0" catches that. Missing data stays missing, as AWS advises for alarms with EC2 actions: an instance that stops reporting for a minute is not proof of a hardware fault, and you do not want it rebooted for that.

Check it worked

Bash
aws cloudwatch describe-alarms --alarm-names alarms-demo-system-check-recover \
  --query 'MetricAlarms[0].AlarmActions' --output text

It prints two ARNs: one starting arn:aws:automate: and ending :ec2:recover, and your topic's ARN.

Step 6 · Alarm on any Lambda error

Lambda's Errors metric counts invocations that ended in a function error: an exception, a timeout, or running out of memory. The Sum over a period is the number of failed calls. For a function that should never fail, one error is worth an email.

This alarm needs a different choice for missing data. Lambda sends Errors only when the function runs, so a function nobody called this hour has no data at all. With the default, the alarm would sit in INSUFFICIENT_DATA most of the time. notBreaching treats silence as "no errors", which is true:

Bash
cd ~/alarms-demo
. ./alarms.env
aws cloudwatch put-metric-alarm \
  --alarm-name alarms-demo-lambda-errors \
  --alarm-description "Lambda function ${FUNCTION_NAME} reported an error" \
  --namespace AWS/Lambda --metric-name Errors \
  --dimensions Name=FunctionName,Value="$FUNCTION_NAME" \
  --statistic Sum --period 60 \
  --evaluation-periods 1 --datapoints-to-alarm 1 \
  --threshold 0 --comparison-operator GreaterThanThreshold \
  --treat-missing-data notBreaching \
  --alarm-actions "$TOPIC_ARN" --ok-actions "$TOPIC_ARN"

A one-minute period with one evaluation period means you hear within a minute or two of the first failure. If the function runs thousands of times a day and a few errors are normal, raise the threshold or alarm on the error rate instead; an alarm that fires every day soon gets ignored.

Check it worked

List all three alarms with their state:

Bash
aws cloudwatch describe-alarms --alarm-name-prefix alarms-demo- \
  --query 'MetricAlarms[].[AlarmName, StateValue, TreatMissingData]' --output text

You see three lines: alarms-demo-cpu-high and alarms-demo-system-check-recover with missing, and alarms-demo-lambda-errors with notBreaching. The Lambda alarm turns OK within a few minutes even if the function never runs.

Step 7 · Force each alarm into ALARM and read the history

You cannot wait for a real outage to learn that the email never arrives. set-alarm-state sets an alarm's state for testing, and CloudWatch runs the actions for that state as if the metric had crossed the line. On the next evaluation, often within seconds, the alarm goes back to its real state and runs the OK actions.

Test the CPU and Lambda alarms:

Bash
cd ~/alarms-demo
. ./alarms.env
for alarm in alarms-demo-cpu-high alarms-demo-lambda-errors; do
  aws cloudwatch set-alarm-state --alarm-name "$alarm" \
    --state-value ALARM --state-reason "Manual test of the email path"
done

Do not force the recovery alarm the same way while its actions are on: the recover action would run too, and could reboot your instance. Turn its actions off, force it, and turn them back on. With actions off, it sends no email either, so this tests the alarm's state and not the delivery, which the other two have just proved:

Bash
aws cloudwatch disable-alarm-actions --alarm-names alarms-demo-system-check-recover
aws cloudwatch set-alarm-state --alarm-name alarms-demo-system-check-recover \
  --state-value ALARM --state-reason "Manual test with actions off"
aws cloudwatch describe-alarms --alarm-names alarms-demo-system-check-recover \
  --query 'MetricAlarms[0].[ActionsEnabled, StateReason]' --output text
aws cloudwatch enable-alarm-actions --alarm-names alarms-demo-system-check-recover

Each alarm keeps 30 days of history: every state change, and every action it ran. Read the state changes for the Lambda alarm:

Bash
aws cloudwatch describe-alarm-history --alarm-name alarms-demo-lambda-errors \
  --history-item-type StateUpdate \
  --query 'AlarmHistoryItems[].[Timestamp, HistorySummary]' --output text

Use --history-item-type Action instead to see whether the SNS publish (or a recover action) succeeded. That is the first place to look when an alarm fired but nobody got an email.

Check it worked

Within a minute or two you get two emails whose subjects start ALARM: "alarms-demo-cpu-high" and ALARM: "alarms-demo-lambda-errors", each with the reason Manual test of the email path. Shortly after, OK: emails follow as the alarms return to their real state. The recovery alarm's line shows False and, unless it has already returned to its real state, your test reason, and aws cloudwatch describe-alarms --alarm-names alarms-demo-system-check-recover --query 'MetricAlarms[0].ActionsEnabled' now prints true. The history lists something like Alarm updated from OK to ALARM and then Alarm updated from ALARM to OK, newest first.

Step 8 · Check what bills, then clean up

On 26 November 2026, the CloudWatch pricing page says:

  • the basic metrics AWS services send, including EC2's 5-minute CPU and the status checks, and Lambda's Errors, cost nothing to collect;
  • the free tier covers 10 alarm metrics a month for standard resolution alarms (periods of 60 seconds or more). Each alarm here watches one metric, so they count as three;
  • beyond that, a standard alarm costs about 0.10 USD per alarm metric per month in US East (N. Virginia), and other Regions differ. High resolution alarms, with periods under 60 seconds, cost more and are not in the free tier;
  • detailed EC2 monitoring (1-minute data) is billed per metric, which is why the CPU alarm here uses 5-minute periods.

SNS email has its own free allowance, on the SNS pricing page. Count the alarms you already have before you add more:

Bash
aws cloudwatch describe-alarms --query 'length(MetricAlarms)' --output text

To remove what this tutorial created, delete the three alarms, then the topic, which also removes its subscriptions. This leaves your instance and function as they were. The case line refuses to go on unless the topic is the demo one:

Bash
cd ~/alarms-demo
. ./alarms.env
case "$TOPIC_ARN" in *:alarms-demo-alerts) echo "Deleting alarms-demo resources" ;; *) echo "TOPIC_ARN is not the demo topic"; false ;; esac
aws cloudwatch delete-alarms --alarm-names \
  alarms-demo-cpu-high alarms-demo-system-check-recover alarms-demo-lambda-errors
aws sns delete-topic --topic-arn "$TOPIC_ARN"
cd ~
rm -rf ~/alarms-demo

If you want to keep the alarms on a real service, skip this step instead, and rename them to something your team will recognise in an inbox at 3 a.m.

Check it worked

aws cloudwatch describe-alarms --alarm-name-prefix alarms-demo- --query 'MetricAlarms[].AlarmName' --output text prints nothing, aws sns list-topics --query 'Topics[].TopicArn' --output text no longer lists alarms-demo-alerts, and ls ~/alarms-demo reports that the folder does not exist.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.