Skip to main content

Monitoring AWS with CloudWatch and CloudTrail

Track AWS health with CloudWatch metrics, logs and alarms, audit every API call with CloudTrail, and detect drift and noncompliance with AWS Config.

Overview and What You Will Learn

CloudWatch, CloudTrail and AWS Config answer three different questions. CloudWatch tells you whether your system is healthy right now, CloudTrail tells you who did what and when, and Config tells you whether your resources are configured the way you intended. You need all three, because none of them replaces the others.

In this lab you will:

  • Read CloudWatch metrics, push a custom metric and understand why memory is not collected by default
  • Send logs to CloudWatch, query them with Logs Insights and route them with subscription filters
  • Build alarms, a composite alarm and an EC2 auto-recovery alarm
  • Use EventBridge to react to events such as a root sign-in
  • Create a CloudTrail trail with S3 data events using CloudFormation
  • Enable Config rules and read compliance results

Why This Matters in Production

A trading platform that fails at market open, a payment API returning 500 errors, and an EC2 instance terminated by an unknown user at 2 AM all need different evidence. CloudWatch shows the error rate climbing, CloudTrail shows which IAM identity terminated the instance and from which IP, and Config shows that a security group was opened to the internet last Tuesday. Without them, engineers debug by guessing.

Core Principles

Each service watches a different thing, and the right tool depends on the question you are asking.

Service Question it answers
CloudWatch Is my system healthy right now?
CloudTrail Who made this API call, and when?
Config Is this resource configured correctly, and how did it change?
flowchart TD A[AWS resources and apps] -->|metrics and logs| CW[CloudWatch] A -->|every API call| CT[CloudTrail] A -->|configuration changes| CF[Config] CW -->|alarm| SNS([SNS or Auto Scaling]) CT -->|events| EB[EventBridge] CF -->|noncompliant| EB EB --> ACT([Notify or remediate]) classDef svc fill:#326CE5,color:#FFFFFF classDef out fill:#10B981,color:#FFFFFF classDef src fill:#DBEAFE,color:#1E293B class CW,CT,CF,EB svc class SNS,ACT out class A src

CloudWatch concepts to know: a namespace groups metrics by service (AWS/EC2), a dimension identifies the exact resource (InstanceId), and a period is the evaluation interval. EC2 sends metrics every 5 minutes by default (basic monitoring) and every 1 minute with detailed monitoring, which costs extra. Custom metrics support 1 minute standard resolution and 1 second high resolution.

Detailed Step-by-Step Practical Lab

Milestone 1: Understand What EC2 Reports and What It Does Not

EC2 publishes CPU, network, disk I/O and status checks without any setup. It does not publish memory usage or disk space used, because the hypervisor cannot see inside the guest operating system. You need the CloudWatch agent for those.

Bash
export AWS_REGION=ap-south-1
export INSTANCE_ID=i-0abc123def456789
aws cloudwatch list-metrics --namespace AWS/EC2 \
--dimensions Name=InstanceId,Value=$INSTANCE_ID \
--query "Metrics[].MetricName" --output text

To collect memory, install the unified CloudWatch agent, attach a role with CloudWatchAgentServerPolicy, then generate and apply a configuration. Store the configuration in Parameter Store so every instance uses the same one.

Bash
# On the instance (Amazon Linux)
sudo dnf install -y amazon-cloudwatch-agent
# Interactive wizard writes a config and can save it to Parameter Store
sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-config-wizard
# Load the config from Parameter Store and start the agent
sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl \
-a fetch-config -m ec2 -c ssm:AmazonCloudWatch-linux -s

The older CloudWatch Logs agent only ships logs. Use the unified agent, which sends logs and system metrics such as memory, swap and disk.

Milestone 2: Push a Custom Metric

Any number your app can measure can be a metric, such as active sessions or queue depth.

Bash
aws cloudwatch put-metric-data \
--namespace "DevOpsNetwork/App" \
--metric-name ActiveSessions \
--value 1247 \
--unit Count \
--dimensions Environment=prod,Service=orders
aws cloudwatch get-metric-statistics \
--namespace "DevOpsNetwork/App" --metric-name ActiveSessions \
--dimensions Name=Environment,Value=prod Name=Service,Value=orders \
--start-time $(date -u -d '15 minutes ago' +%FT%TZ) --end-time $(date -u +%FT%TZ) \
--period 60 --statistics Maximum

Each distinct dimension combination is billed as a separate metric, so avoid high-cardinality dimensions such as user IDs.

Milestone 3: Work with Logs

CloudWatch Logs organizes data into log groups (one per application) and log streams (one per source). Set a retention period on every log group, because the default is to keep logs forever and pay for them forever.

Bash
aws logs put-retention-policy \
--log-group-name /aws/lambda/devops-orders \
--retention-in-days 30
# Query with Logs Insights from the CLI
QUERY_ID=$(aws logs start-query \
--log-group-name /aws/lambda/devops-orders \
--start-time $(date -d '1 hour ago' +%s) --end-time $(date +%s) \
--query-string 'fields @timestamp, @message | filter @message like /ERROR/ | sort @timestamp desc | limit 20' \
--query queryId --output text)
sleep 5
aws logs get-query-results --query-id $QUERY_ID

Useful Logs Insights queries:

Bash
# Errors per 5 minutes
fields @timestamp, @message
| filter @message like /Exception/
| stats count(*) as errors by bin(5m)
# Slowest Lambda invocations
filter @type = "REPORT"
| stats avg(@duration), max(@duration) by bin(5m)
| sort max(@duration) desc

Logs Insights searches stored data. For real-time routing, use subscription filters, which stream matching events to Lambda, Kinesis Data Streams or Firehose. A log group allows at most two subscription filters. Exporting to S3 with CreateExportTask is for archiving and can take hours.

Bash
aws logs put-subscription-filter \
--log-group-name /aws/lambda/devops-orders \
--filter-name errors-to-slack \
--filter-pattern "ERROR" \
--destination-arn arn:aws:lambda:ap-south-1:123456789012:function:slack-alerts
Milestone 4: Create Alarms

An alarm watches one metric and moves between OK, ALARM and INSUFFICIENT_DATA. Using "M out of N" datapoints avoids alarming on a single spike.

Bash
aws sns create-topic --name devops-monitoring-alerts
aws sns subscribe \
--topic-arn arn:aws:sns:ap-south-1:123456789012:devops-monitoring-alerts \
--protocol email --notification-endpoint ops-team@devops.in
# Confirm the subscription from your inbox
# CPU above 80 percent for 3 of the last 5 one-minute periods
aws cloudwatch put-metric-alarm \
--alarm-name high-cpu-prod \
--namespace AWS/EC2 --metric-name CPUUtilization \
--dimensions Name=InstanceId,Value=$INSTANCE_ID \
--statistic Average --period 60 \
--evaluation-periods 5 --datapoints-to-alarm 3 \
--threshold 80 --comparison-operator GreaterThanThreshold \
--treat-missing-data notBreaching \
--alarm-actions arn:aws:sns:ap-south-1:123456789012:devops-monitoring-alerts
# Test the notification path without waiting for real load
aws cloudwatch set-alarm-state \
--alarm-name high-cpu-prod --state-value ALARM --state-reason "pipeline test"

Alarm actions can notify SNS, scale an Auto Scaling group, or stop, terminate, reboot or recover an EC2 instance. Combine alarms into a composite alarm to cut noise, so you are only paged when CPU and memory are both high.

Bash
aws cloudwatch put-composite-alarm \
--alarm-name prod-web-saturated \
--alarm-rule 'ALARM("high-cpu-prod") AND ALARM("high-memory-prod")' \
--alarm-actions arn:aws:sns:ap-south-1:123456789012:devops-oncall

EC2 auto-recovery restarts an instance on healthy hardware when the system status check fails. It keeps the instance ID, private IP, Elastic IP and metadata, but instance store data is lost.

Bash
aws cloudwatch put-metric-alarm \
--alarm-name recover-web-1 \
--namespace AWS/EC2 --metric-name StatusCheckFailed_System \
--dimensions Name=InstanceId,Value=$INSTANCE_ID \
--statistic Maximum --period 60 --evaluation-periods 2 \
--threshold 1 --comparison-operator GreaterThanOrEqualToThreshold \
--alarm-actions arn:aws:automate:ap-south-1:ec2:recover

Four specialized CloudWatch features build on this: Container Insights (ECS and EKS metrics and logs), Lambda Insights (cold starts, memory and CPU via a Lambda layer), Contributor Insights (top talkers, such as the IPs causing most 404s) and Application Insights (automatic dashboards and anomaly findings for an application stack).

Milestone 5: React to Events with EventBridge

EventBridge routes events from AWS services to targets. A rule matches an event pattern or runs on a schedule (use EventBridge Scheduler for one-off and flexible schedules). This stack notifies the security team on any root user console sign-in.

YAML
# root-login-alert.yaml
AWSTemplateFormatVersion: "2010-09-09"
Description: Alert on root user console sign-in
Resources:
AlertsTopic:
Type: AWS::SNS::Topic
Properties:
Subscription:
- Protocol: email
Endpoint: security@devops.in
AlertsTopicPolicy:
Type: AWS::SNS::TopicPolicy
Properties:
Topics: [!Ref AlertsTopic]
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: events.amazonaws.com
Action: sns:Publish
Resource: !Ref AlertsTopic
RootLoginRule:
Type: AWS::Events::Rule
Properties:
Description: Root user signed in to the console
EventPattern:
source: [aws.signin]
detail-type: [AWS Console Sign In via CloudTrail]
detail:
userIdentity:
type: [Root]
Targets:
- Arn: !Ref AlertsTopic
Id: notify-security

Console sign-in events are recorded in the region of the sign-in endpoint, often us-east-1, so deploy this stack in us-east-1 as well as your main region. A root sign-in alert is also a good first target for an automated response, but a human should always review the event.

Milestone 6: Create a CloudTrail Trail

CloudTrail is enabled by default and keeps 90 days of management events in Event History, free. To keep events longer, or to record data events, create a trail that writes to S3. Management events (creating an instance, editing a policy) are logged by default. Data events, such as S3 GetObject and Lambda Invoke, are not, and must be enabled explicitly at extra cost. CloudTrail Insights separately flags unusual API activity.

YAML
# audit-trail.yaml
AWSTemplateFormatVersion: "2010-09-09"
Description: Organization audit trail with S3 data events
Parameters:
SensitiveBucketName:
Type: String
Description: Bucket whose object-level activity must be logged
Resources:
TrailBucket:
Type: AWS::S3::Bucket
DeletionPolicy: Retain
Properties:
VersioningConfiguration:
Status: Enabled
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
TrailBucketPolicy:
Type: AWS::S3::BucketPolicy
Properties:
Bucket: !Ref TrailBucket
PolicyDocument:
Version: "2012-10-17"
Statement:
- Sid: AclCheck
Effect: Allow
Principal:
Service: cloudtrail.amazonaws.com
Action: s3:GetBucketAcl
Resource: !GetAtt TrailBucket.Arn
Condition:
StringEquals:
aws:SourceArn: !Sub "arn:aws:cloudtrail:${AWS::Region}:${AWS::AccountId}:trail/prod-audit-trail"
- Sid: Write
Effect: Allow
Principal:
Service: cloudtrail.amazonaws.com
Action: s3:PutObject
Resource: !Sub "${TrailBucket.Arn}/AWSLogs/${AWS::AccountId}/*"
Condition:
StringEquals:
aws:SourceArn: !Sub "arn:aws:cloudtrail:${AWS::Region}:${AWS::AccountId}:trail/prod-audit-trail"
AuditTrail:
Type: AWS::CloudTrail::Trail
DependsOn: TrailBucketPolicy
Properties:
TrailName: prod-audit-trail
S3BucketName: !Ref TrailBucket
IsLogging: true
IsMultiRegionTrail: true
IncludeGlobalServiceEvents: true
EnableLogFileValidation: true
EventSelectors:
- ReadWriteType: All
IncludeManagementEvents: true
DataResources:
- Type: AWS::S3::Object
Values:
- !Sub "arn:aws:s3:::${SensitiveBucketName}/"
Bash
aws cloudformation deploy \
--stack-name audit-trail \
--template-file audit-trail.yaml \
--parameter-overrides SensitiveBucketName=devops-customer-data-mumbai
# Find who deleted a security group rule in the last day
aws cloudtrail lookup-events \
--lookup-attributes AttributeKey=EventName,AttributeValue=RevokeSecurityGroupIngress \
--max-results 5 \
--query "Events[].[EventTime,Username,EventName]" --output table

For months of history, query the trail logs in S3 with Athena or use CloudTrail Lake. Log file validation lets you prove that logs were not altered.

Security

Send trail logs to a separate, locked-down log archive account with Object Lock or restricted delete permissions. If an attacker compromises a workload account, they should not be able to erase the evidence.

Milestone 7: Turn On Config and Add Rules

Config records the configuration of your resources over time and evaluates them against rules. It detects and reports, and it does not block changes. Turn it on from the console (Config, Get started, record all resources, create the delivery bucket), then add managed rules. There are hundreds of managed rules, and you can write custom ones with Lambda.

Bash
# Rules that make a good starting set (managed rule identifiers)
# INCOMING_SSH_DISABLED (console name: restricted-ssh)
# ENCRYPTED_VOLUMES
# S3_BUCKET_VERSIONING_ENABLED
# ROOT_ACCOUNT_MFA_ENABLED
# REQUIRED_TAGS
# Ask for an evaluation now and read compliance
aws configservice start-config-rules-evaluation --config-rule-names restricted-ssh
aws configservice describe-compliance-by-config-rule \
--query "ComplianceByConfigRules[].[ConfigRuleName,Compliance.ComplianceType]" --output table
aws configservice get-compliance-details-by-config-rule \
--config-rule-name restricted-ssh --compliance-types NON_COMPLIANT
# History of how one resource changed
aws configservice get-resource-config-history \
--resource-type AWS::EC2::SecurityGroup --resource-id sg-0abc123def456789 --limit 5

A rule that flags a noncompliant resource can trigger automatic remediation with an SSM Automation document, for example one that removes an open SSH rule from a security group. Prevention belongs in IAM policies and Service Control Policies, and Config provides the continuous detection and cleanup behind them. Use a Config aggregator to view compliance across an organization, and watch costs because Config bills per recorded configuration item.

Milestone 8: Clean Up
Bash
aws cloudwatch delete-alarms --alarm-names high-cpu-prod recover-web-1 prod-web-saturated
aws sns delete-topic --topic-arn arn:aws:sns:ap-south-1:123456789012:devops-monitoring-alerts
aws cloudformation delete-stack --stack-name audit-trail
# The trail bucket is retained, empty and delete it yourself when finished
# Stop Config recording in the console if you do not want ongoing charges

Production Best Practices & Common Pitfalls

  1. Set log retention on every log group. Never leave logs at "never expire" by accident.
  2. Alert on symptoms users feel. Error rate and latency matter more than CPU.
  3. Use composite alarms and M-of-N datapoints. They reduce pages for harmless spikes.
  4. Enable data events for sensitive S3 buckets. They are off by default.
  5. Protect the audit trail. Separate account, log file validation and restricted deletion.
  6. Alert on high-risk events. Root sign-ins, IAM policy changes and CloudTrail being stopped.
  7. Use Config for continuous detection with remediation. Use SCPs and IAM policies for prevention.
Common Mistake

Treating Config rules as preventive controls. If someone opens port 22 to the world, Config reports it after the change already happened. Use IAM and SCPs to prevent it, and Config to detect and repair.

Remember

EC2 does not report memory by default, and CloudTrail does not log S3 object reads and writes by default. Both need explicit setup.

Tip

Run aws cloudwatch set-alarm-state after creating any alarm to prove the notification really reaches a person. An untested alarm is a guess.

Quick Reference & Troubleshooting Commands

Command Description
aws cloudwatch put-metric-alarm Create an alarm
aws cloudwatch set-alarm-state Force a state to test notifications
aws logs start-query Run a Logs Insights query
aws logs put-retention-policy Set log retention
aws cloudtrail lookup-events Search 90 days of management events
aws configservice describe-compliance-by-config-rule Show rule compliance
Symptom Likely cause and fix
No memory metrics for EC2 CloudWatch agent not installed or not configured
Alarm stuck in INSUFFICIENT_DATA Metric not being published, or wrong dimensions or period
No S3 object events in CloudTrail Data events not enabled for that bucket
Config rule shows no results Config recorder not running or rule still evaluating
Root login alert never fires Rule deployed in the wrong region, also deploy in us-east-1

Resources

AWS Direct Connect vs VPN: Run Both as Failover

AWS Direct Connect vs VPN: Run Both as Failover

Run AWS Direct Connect as primary and Site-to-Site VPN as BGP failover. Size the backup, set route preference and test it before an outage does.

10 min read•Aug 2026
Lambda vs Fargate vs EC2 Spot: The Cost Crossover

Lambda vs Fargate vs EC2 Spot: The Cost Crossover

Lambda vs Fargate vs EC2 Spot, at the crossover where Lambda stops being cheaper — 2026 pricing, invocation thresholds, and interruption math.

5 min read•Aug 2026
Secrets Manager vs Parameter Store vs Vault

Secrets Manager vs Parameter Store vs Vault

Secrets Manager vs Parameter Store vs Vault: cost math, rotation, dynamic secrets and a decision flow, plus the Vault, IBM and OpenBao licensing context.

10 min read•Aug 2026
AWS VPC Security: Hardening Every Layer

AWS VPC Security: Hardening Every Layer

Harden your AWS VPC in layers: subnets, Security Groups, NACLs, Flow Logs, endpoints, and IAM conditions, with CLI examples for production.

10 min read•Jul 2026
Event-Driven Architecture on AWS Explained

Event-Driven Architecture on AWS Explained

Build event-driven systems on AWS with SQS, SNS, EventBridge and Kinesis: fan-out, DLQs, idempotent consumers and queue-based scaling.

11 min read•Jul 2026
S3 vs RDS vs DynamoDB: Choosing AWS Storage

S3 vs RDS vs DynamoDB: Choosing AWS Storage

Choosing S3, RDS, or DynamoDB wrong costs you in performance, cost, and scalability. Here is a practical decision guide based on your actual access patterns.

5 min read•Jul 2026
AWS Cost Optimisation: 8 Actions That Cut Bills

AWS Cost Optimisation: 8 Actions That Cut Bills

Cut your AWS bill without re-architecting: eight ordered steps from anomaly alerts and tagging to rightsizing, VPC endpoints, Savings Plans and Spot.

11 min read•Jul 2026
EC2 vs Lambda vs Fargate: Choosing AWS Compute

EC2 vs Lambda vs Fargate: Choosing AWS Compute

Choose between EC2, Lambda and Fargate using traffic shape, state and runtime limits, with worked cost break-evens instead of rules of thumb.

11 min read•Jul 2026

Explore More in AWS DevOps, Cost, and Machine Learning

All 6 Topics

Frequently Asked Questions

Is Monitoring AWS with CloudWatch and CloudTrail free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Monitoring AWS with CloudWatch and CloudTrail topic cover?

Track AWS health with CloudWatch metrics, logs and alarms, audit every API call with CloudTrail, and detect drift and noncompliance with AWS Config.

Found a mistake, an outdated step or a broken link?