Sub topic 7
Alarm actions and SNS notifications
This chapter assumes you can create a metric alarm with put-metric-alarm and that you know what an SNS topic is. You should also be comfortable with IAM policies and the AWS CLI. An alarm that only changes color in the console does not help at 3 a.m. Alarm actions make an alarm notify people or change your infrastructure.
How alarm actions are triggered
An alarm is always in one of three states:
OK: the metric is within the threshold.ALARM: the threshold is breached for enough data points.INSUFFICIENT_DATA: not enough data to decide.
You attach a list of actions to each state: --alarm-actions, --ok-actions and --insufficient-data-actions. CloudWatch runs the actions of a state when the alarm changes into that state. It does not run them on every evaluation. An alarm that stays in ALARM for six hours sends one notification at the start and none after that, unless it leaves and re-enters ALARM.
A new alarm starts in INSUFFICIENT_DATA. Moving from there to OK runs the OK actions, so you may get an "OK" message right after creating an alarm. This is normal.
Types of actions
An action is an ARN. The common types are:
| Action | ARN pattern | Typical use |
|---|---|---|
| SNS topic | `arn:aws:sns:region:account:topic` | Email, SMS, chat, webhooks, Lambda |
| EC2 reboot | `arn:aws:automate:region:ec2:reboot` | Restart a hung instance |
| EC2 recover | `arn:aws:automate:region:ec2:recover` | Move an instance off failed hardware |
| EC2 stop or terminate | `arn:aws:automate:region:ec2:stop` or `...:terminate` | Shut down idle instances |
| Auto Scaling policy | ARN of a scaling policy | Add or remove capacity |
| Systems Manager | OpsItem or Incident Manager ARN | Open a ticket or incident |
SNS is the most flexible choice because one topic can fan out to many subscribers. For anything more elaborate than a single action, you can send alarm state changes to EventBridge instead. A later chapter covers that.
Create the topic and subscribe
An SNS topic is a named channel. A subscription connects an endpoint, such as an email address, to that topic.
aws sns create-topic --name ops-alerts
aws sns subscribe \
--topic-arn arn:aws:sns:us-east-1:111122223333:ops-alerts \
--protocol email \
--notification-endpoint [email protected]An email subscription stays in PendingConfirmation until the recipient clicks the link in the confirmation message. A pending subscription receives nothing. This is the most common reason a "working" alarm sends no email. You can check with aws sns list-subscriptions-by-topic. Look for a real subscription ARN instead of the text PendingConfirmation.
Attach the topic to an alarm
The next command creates an alarm that notifies the topic when it fires and again when it recovers. It also notifies on missing data.
aws cloudwatch put-metric-alarm \
--alarm-name high-cpu-web \
--namespace AWS/EC2 \
--metric-name CPUUtilization \
--dimensions Name=InstanceId,Value=i-0123456789abcdef0 \
--statistic Average \
--period 300 \
--evaluation-periods 3 \
--datapoints-to-alarm 2 \
--threshold 80 \
--comparison-operator GreaterThanOrEqualToThreshold \
--treat-missing-data notBreaching \
--alarm-actions arn:aws:sns:us-east-1:111122223333:ops-alerts \
--ok-actions arn:aws:sns:us-east-1:111122223333:ops-alerts \
--insufficient-data-actions arn:aws:sns:us-east-1:111122223333:ops-alertsSending the OK notification to the same topic is useful. People learn that an incident has ended without checking the console. Sending INSUFFICIENT_DATA to the same topic can be noisy when you use notBreaching, since that setting mostly keeps the alarm out of that state. Choose which states each audience needs.
put-metric-alarm replaces the whole alarm definition. If you re-run it without --ok-actions, the OK actions are removed. Always pass the complete set of options when you update an alarm.
Test the whole path
Do not wait for a real incident to learn whether notifications work. set-alarm-state forces a state temporarily:
aws cloudwatch set-alarm-state \
--alarm-name high-cpu-web \
--state-value ALARM \
--state-reason "Testing notification path"This runs the alarm actions as a real transition would. The alarm returns to its true state at the next evaluation, which runs the OK actions if the real state is OK. Then check what happened:
aws cloudwatch describe-alarm-history \
--alarm-name high-cpu-web \
--history-item-type ActionThe history shows whether each action succeeded or failed, and the error text if it failed. This is the first place to look when no message arrives.
Permissions and encryption
Alarms in the same account can publish to an SNS topic using the default topic policy. If the topic is in another account, its policy must allow the CloudWatch service principal. Save this as topic-policy.json:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowCloudWatchAlarms",
"Effect": "Allow",
"Principal": { "Service": "cloudwatch.amazonaws.com" },
"Action": "sns:Publish",
"Resource": "arn:aws:sns:us-east-1:111122223333:ops-alerts",
"Condition": {
"ArnLike": {
"aws:SourceArn": "arn:aws:cloudwatch:us-east-1:444455556666:alarm:*"
}
}
}
]
}Apply it with:
aws sns set-topic-attributes \
--topic-arn arn:aws:sns:us-east-1:111122223333:ops-alerts \
--attribute-name Policy \
--attribute-value file://topic-policy.jsonSetting Policy replaces the whole existing policy. Merge in the default statements first if you still need them. The aws:SourceArn condition limits the permission to alarms from one account, which stops other services from publishing to your topic.
If the topic uses server-side encryption, the AWS managed key alias/aws/sns does not work for alarm notifications. Its key policy cannot be changed to allow CloudWatch. Use a customer managed KMS key whose key policy allows cloudwatch.amazonaws.com to call kms:Decrypt and kms:GenerateDataKey*.
Common errors
- Region mismatch. An alarm can notify an SNS topic only in the same region. If you need alerts from several regions, create a topic in each region, or forward them with EventBridge.
- Unconfirmed subscription. The message is published, but nobody receives it.
- Silent action failures. The alarm changes state, but the SNS publish is denied by the topic or key policy. The alarm looks fine in the console. Only
describe-alarm-historyshows the failure. - Expecting repeated reminders. Actions run on transitions only. If you need repeated paging, use an incident tool such as Incident Manager or a paging service that escalates from the first notification.
- Dangerous EC2 actions. A
terminateaction on a metric that goes missing can delete healthy instances. Pair destructive actions with--treat-missing-data notBreachingorignore, and test on a non-production instance first.
Reducing noise
Each alarm sends its own notifications, so one failing dependency can fan out into dozens of messages. Composite alarms combine several alarms with a rule such as ALARM(a) AND ALARM(b) and send a single notification. When you use them, you can leave the child alarms without actions and put the SNS action only on the composite alarm. A later chapter covers this.
Exercise
A metric alarm on an EC2 instance has been in ALARM for two hours, but your team received only one email, sent when it first fired. Is something broken? Name the reason, and how you would get another notification.
Show answer
Nothing is broken. CloudWatch runs alarm actions only when the alarm transitions into a state, so a long-running ALARM state sends one notification. To get another message, the alarm must leave ALARM and enter it again, which also sends an OK message in between. You can also force this with set-alarm-state when testing. For repeated reminders during a long incident, use a tool that escalates from the first notification, such as Incident Manager.
Exercise
You subscribed an email address to an SNS topic and created an alarm with that topic in --alarm-actions. You ran set-alarm-state and no email arrived. Give three things to check, in order.
Show answer
First, run aws sns list-subscriptions-by-topic and confirm the subscription is not PendingConfirmation. Second, run aws cloudwatch describe-alarm-history with --history-item-type Action to see whether the SNS publish failed, and read the error. Third, check the topic policy (for cross-account alarms), the KMS key policy if the topic is encrypted with a customer managed key, and that the alarm and topic are in the same region.