Sub topic 9
Collecting memory, disk, and log files with the CloudWatch agent
This chapter assumes you know how metrics, namespaces, and dimensions fit together. It also assumes you can launch an EC2 instance, attach an IAM role to it, and run AWS CLI commands. You should know what a log group and a log stream are.
Why the agent exists
EC2 publishes CPU, network, and disk I/O metrics to CloudWatch automatically. The hypervisor, the layer that runs your virtual machine, measures these from outside the instance. It cannot see inside the operating system. Memory use, filesystem free space, swap, and application log files are invisible to it.
The CloudWatch agent is a program you install on the instance. It reads those values from inside the operating system and sends them to CloudWatch. It does two jobs:
- It publishes metrics, such as
mem_used_percentanddisk used_percent. These are custom metrics, so they appear in theCWAgentnamespace by default, not inAWS/EC2. - It ships log files to CloudWatch Logs, where each file becomes a log stream inside a log group.
The agent also runs on on-premises servers and on Windows. This chapter uses Amazon Linux on EC2.
Step 1: Give the instance permission
The agent calls the CloudWatch APIs with the credentials of the instance's IAM role. Without the right permissions it starts, then fails silently or logs access-denied errors in its own log file.
Attach the AWS managed policy CloudWatchAgentServerPolicy to the instance role. It allows cloudwatch:PutMetricData and the CloudWatch Logs write actions, and it allows reading the agent configuration from Systems Manager Parameter Store.
aws iam attach-role-policy \
--role-name web-instance-role \
--policy-arn arn:aws:iam::aws:policy/CloudWatchAgentServerPolicyThe role must already be part of an instance profile that is attached to the instance.
Step 2: Install the agent
On Amazon Linux 2023 the agent is available from the package repository.
sudo dnf install -y amazon-cloudwatch-agentOn other distributions, download the package from the AWS download URL for your OS and architecture, then install it with rpm or dpkg. You can also install it fleet-wide with Systems Manager Run Command and the AWS-ConfigureAWSPackage document.
Step 3: Write the configuration
The agent reads a JSON file with three top-level sections: agent, metrics, and logs. This file collects memory and disk usage every 60 seconds and ships one application log.
{
"agent": { "metrics_collection_interval": 60 },
"metrics": {
"append_dimensions": { "InstanceId": "${aws:InstanceId}" },
"metrics_collected": {
"mem": { "measurement": ["mem_used_percent"] },
"disk": { "measurement": ["used_percent"], "resources": ["*"] }
}
},
"logs": {
"logs_collected": {
"files": {
"collect_list": [
{
"file_path": "/var/log/app/app.log",
"log_group_name": "/app/web",
"log_stream_name": "{instance_id}"
}
]
}
}
}
}Each part does the following:
| Setting | Effect |
|---|---|
| `metrics_collection_interval` | Seconds between samples. The default is 60. |
| `append_dimensions` | Adds a dimension to every metric. `${aws:InstanceId}` is replaced with the instance ID at runtime. |
| `mem` and `disk` | Choose which plugins run and which measurements each one reports. |
| `resources: ["*"]` | Reports every mounted filesystem. List specific mount points to limit this. |
| `file_path` | The file to tail. Glob patterns such as `/var/log/app/*.log` are allowed. |
| `log_group_name` | The target log group. The agent creates it if it does not exist. |
| `log_stream_name` | The stream name. `{instance_id}` gives one stream per instance. |
Save the file as /opt/aws/amazon-cloudwatch-agent/etc/config.json, or store it in Parameter Store so many instances can share it.
Step 4: Start the agent with the configuration
The amazon-cloudwatch-agent-ctl script loads a configuration and starts the service.
sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl \
-a fetch-config -m ec2 -s \
-c file:/opt/aws/amazon-cloudwatch-agent/etc/config.jsonThe flags mean: -a fetch-config loads a configuration, -m ec2 sets the mode, -s starts the agent after loading, and -c names the source. To load from Parameter Store instead, use -c ssm:AmazonCloudWatch-linux, where the value after ssm: is your parameter name.
Check that it is running:
sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a statusThe output is JSON and shows "status": "running" when the agent is healthy. If it is not, read /opt/aws/amazon-cloudwatch-agent/logs/amazon-cloudwatch-agent.log.
Step 5: Find the data
Metrics appear in the CWAgent namespace after a minute or two. List them with the CLI:
aws cloudwatch list-metrics --namespace CWAgentThe dimensions on each metric depend on the plugin. A disk metric carries InstanceId from append_dimensions, plus path, device, and fstype. A memory metric carries only InstanceId. This matters because a metric is identified by its exact set of dimensions. An alarm on mem_used_percent must name the same dimensions you see in list-metrics, or it will watch a metric that has no data.
Logs appear in the /app/web log group, in a stream named after the instance ID.
Edge cases and common errors
No data appears
Work through these checks in order:
- Confirm the agent status is
running. - Confirm the instance role has the policy and that the instance can reach CloudWatch endpoints. In a private subnet, this needs a NAT gateway or VPC endpoints for monitoring and logs.
- Read the agent log for
AccessDeniedorNoCredentialProviders. - Check that you are looking in the same region as the instance.
Wrong dimensions on alarms
Adding or removing an entry in append_dimensions creates a new metric. The old metric stops receiving data. Existing alarms stay on the old one and go to INSUFFICIENT_DATA. Decide on your dimensions before you build alarms on them.
Log file is not picked up
The agent needs read permission on the file. It runs as root by default, but if you set run_as_user, that user must be able to read the log. The agent tails from the end of a file when it first starts, so lines written before the first start are not sent. Log rotation is handled for common patterns, but a glob that matches rotated copies such as app.log.1 can send old data twice. Prefer a pattern that matches only the active file.
Cost from the disk plugin
"resources": ["*"] creates one metric per filesystem and per measurement. On hosts with many mounts, such as containers or snap volumes, this adds many billable custom metrics. List only the mount points you need.
Configuration changes do not apply
Editing the file does nothing until you run fetch-config again. The command restarts the agent with the new configuration.
Using the metrics in an alarm
Once memory data flows, alarm on it the way you would on any metric. Use the namespace CWAgent and the exact dimensions shown by list-metrics.
aws cloudwatch put-metric-alarm \
--alarm-name high-memory-web \
--namespace CWAgent \
--metric-name mem_used_percent \
--dimensions Name=InstanceId,Value=i-0123456789abcdef0 \
--statistic Average \
--period 60 \
--evaluation-periods 5 \
--datapoints-to-alarm 3 \
--threshold 90 \
--comparison-operator GreaterThanOrEqualToThreshold \
--treat-missing-data breaching \
--alarm-actions arn:aws:sns:us-east-1:111122223333:ops-alertsHere missing data is treated as breaching. If the agent stops, the instance has no memory data, and you want to hear about it. That choice differs from the CPU alarm in an earlier chapter, because CPU data comes from EC2 itself and does not stop when the agent fails.
Exercise
You add "disk": {"measurement": ["used_percent"], "resources": ["*"]} and later change append_dimensions to also include ImageId. Your existing disk alarm moves to INSUFFICIENT_DATA. Why, and what do you do?
Show answer
A metric is identified by its namespace, name, and exact set of dimensions. Adding ImageId created a new metric with a different dimension set, so the old metric no longer receives data and the alarm watches it. Recreate the alarm with the new dimension set, matching what aws cloudwatch list-metrics --namespace CWAgent shows. To avoid this, decide on the dimension set before building alarms.
Exercise
The agent status is running, but the /app/web log group is empty. Name two likely causes.
Show answer
Possible causes include: the agent user cannot read /var/log/app/app.log; the file had no new lines written after the agent started, since it tails from the end; the file_path does not match the real file; the instance role lacks CloudWatch Logs permissions or has no network path to the Logs endpoint; or you are checking the wrong region. The agent log file shows access-denied or file-not-found errors.