Sub topic 17
Monitoring instances and status checks
This chapter assumes you can launch an instance with the AWS CLI, understand instance states (running, stopped, terminated), and know what an IAM role is. You will learn which signals EC2 reports by default, how status checks work, and how to alarm on failures. You will also learn the most common mistakes people make when they read these signals.
What EC2 reports without any setup
EC2 sends metrics to Amazon CloudWatch automatically. CloudWatch is the AWS service that stores time-series metrics, evaluates alarms, and triggers actions. Metrics for the AWS/EC2 namespace are collected at the hypervisor level, which means AWS measures them from outside your instance.
The main default metrics are:
CPUUtilization: the percentage of allocated compute units in use.NetworkInandNetworkOut: bytes received and sent on all network interfaces.DiskReadOpsandDiskWriteOps: operations on instance store volumes only.StatusCheckFailed,StatusCheckFailed_Instance, andStatusCheckFailed_System: the status check results, reported as 0 (passing) or 1 (failing).
Basic monitoring publishes data every 5 minutes at no charge. Detailed monitoring publishes every 1 minute for an extra fee. Enable it when you need faster alarms or finer graphs.
aws ec2 monitor-instances --instance-ids i-0123456789abcdef0What the hypervisor cannot see
Because the metrics come from outside the instance, EC2 does not report memory use or disk space. It also cannot see processes inside the operating system. To get those, install the CloudWatch agent on the instance and give the instance an IAM role that allows it to publish metrics. The agent publishes to the CWAgent namespace by default.
Two gotchas follow from this:
DiskReadOpsandDiskWriteOpsdo not cover EBS volumes. EBS has its own metrics in theAWS/EBSnamespace, such asVolumeReadOpsandVolumeQueueLength.- On burstable instances such as the T3 family, a low
CPUUtilizationcan still hide a problem. WatchCPUCreditBalanceas well. When credits run out, the instance is throttled to its baseline.
Status checks
EC2 runs two automated checks on every running instance once a minute. They answer different questions, and they have different fixes.
| Check | What it tests | Typical causes of failure | Usual fix |
|---|---|---|---|
| System status check | The AWS infrastructure hosting the instance | Loss of network connectivity, loss of power, host software or hardware problems | Stop and start the instance so it moves to a new host, or let automatic recovery do it |
| Instance status check | The software and network configuration of your instance | Failed file system checks, wrong network configuration, kernel panic, exhausted memory | Reboot, or fix the configuration, then reboot |
A rule of thumb: if the system check fails, the problem is AWS's side and moving hosts fixes it. If only the instance check fails, the problem is inside your instance and you must fix it.
EC2 also reports an attached EBS status check for volumes. It tells you whether a volume can complete I/O.
Reading status checks from the CLI
describe-instance-status returns status only for running instances by default. Add --include-all-instances to see stopped ones too.
aws ec2 describe-instance-status \
--instance-ids i-0123456789abcdef0 \
--query 'InstanceStatuses[].[InstanceId,InstanceState.Name,SystemStatus.Status,InstanceStatus.Status]' \
--output tableA healthy instance shows ok in both columns. The value initializing appears for the first few minutes after launch. The value impaired means a check is failing. insufficient-data means EC2 has not yet collected enough results.
Alarms and automatic actions
A CloudWatch alarm watches one metric and changes state when the metric crosses a threshold for a number of periods. The states are OK, ALARM, and INSUFFICIENT_DATA. An alarm can notify an Amazon SNS topic, or it can run an EC2 action directly.
The following command creates an alarm that recovers an instance when the system status check fails for two consecutive minutes. The recover action works on supported instance types, and it keeps the instance ID, private IP addresses, Elastic IP addresses, and metadata. The instance restarts, so memory contents are lost.
aws cloudwatch put-metric-alarm \
--alarm-name tutorial-web-system-recover \
--namespace AWS/EC2 \
--metric-name StatusCheckFailed_System \
--dimensions Name=InstanceId,Value=i-0123456789abcdef0 \
--statistic Maximum \
--period 60 \
--evaluation-periods 2 \
--threshold 1 \
--comparison-operator GreaterThanOrEqualToThreshold \
--alarm-actions arn:aws:automate:us-east-1:ec2:recoverReplace us-east-1 with your Region. The alarm action ARN must name the same Region as the instance.
A second alarm that notifies you about high CPU would use CPUUtilization, Average, a 300-second period, and a topic ARN in --alarm-actions. For example, arn:aws:sns:us-east-1:123456789012:ops-alerts sends a message to anyone subscribed to that topic.
Choosing alarm settings
- Use
Maximumfor status check metrics. An average could dilute a single failing minute. - Use several evaluation periods for noisy metrics like CPU. One spike should not wake someone at night.
- Set
--treat-missing-datadeliberately. A stopped instance emits no metrics. With the defaultmissingsetting, an alarm keeps its previous state, which may surprise you.
Reading metrics from the CLI
You can query any metric with get-metric-statistics. The command below returns average CPU in 5-minute buckets. The date syntax shown is for GNU date on Linux.
aws cloudwatch get-metric-statistics \
--namespace AWS/EC2 \
--metric-name CPUUtilization \
--dimensions Name=InstanceId,Value=i-0123456789abcdef0 \
--start-time "$(date -u -d '-1 hour' +%Y-%m-%dT%H:%M:%SZ)" \
--end-time "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
--period 300 \
--statistics Average \
--output tableCommon errors
- Alarm stuck in
INSUFFICIENT_DATA. The instance is stopped, the dimension has the wrong instance ID, or the alarm is in a different Region than the instance. - Recovery never happens. The instance type or configuration does not support the recover action, for example an instance with instance store volumes. Check the supported list, and use a reboot or an Auto Scaling replacement instead.
- Memory alarm cannot be created. There is no default memory metric. Install the CloudWatch agent first and use the
CWAgentnamespace. - Status check shows
impairedright after launch. Wait a few minutes, since the checks need time to initialize. If a failure persists, read the console output withaws ec2 get-console-output.
aws ec2 get-console-output --instance-id i-0123456789abcdef0 --latest --output textWhere monitoring leads
Alarms are the hook for automation. In a later chapter, an Auto Scaling group uses the same kind of metric to add or remove instances, and a load balancer health check decides whether traffic should reach an instance. Status checks and load balancer health checks are different: the first tests the instance and host, the second tests whether your application answers requests. An instance can pass every status check while its web server is down.
Exercise
An instance passes both status checks, but users report that the website returns errors. Why can this happen, and what would you add to detect it?
Show answer
Status checks only test the host infrastructure and the instance's basic software and network configuration. They do not test your application. Add an application-level check, such as a load balancer health check against a URL, and publish application or memory metrics with the CloudWatch agent so you can alarm on them.
Exercise
You want an alarm that restarts an instance on new hardware when the AWS host fails. Which metric, statistic, and alarm action do you use?
Show answer
Use the StatusCheckFailed_System metric with the Maximum statistic, and set the alarm action to arn:aws:automate:REGION:ec2:recover, with your own Region in place of REGION.