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? |
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.
export AWS_REGION=ap-south-1export INSTANCE_ID=i-0abc123def456789 aws cloudwatch list-metrics --namespace AWS/EC2 \ --dimensions Name=InstanceId,Value=$INSTANCE_ID \ --query "Metrics[].MetricName" --output textTo 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.
# On the instance (Amazon Linux)sudo dnf install -y amazon-cloudwatch-agent # Interactive wizard writes a config and can save it to Parameter Storesudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-config-wizard # Load the config from Parameter Store and start the agentsudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl \ -a fetch-config -m ec2 -c ssm:AmazonCloudWatch-linux -sThe 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.
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 MaximumEach 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.
aws logs put-retention-policy \ --log-group-name /aws/lambda/devops-orders \ --retention-in-days 30 # Query with Logs Insights from the CLIQUERY_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 5aws logs get-query-results --query-id $QUERY_IDUseful Logs Insights queries:
# Errors per 5 minutesfields @timestamp, @message| filter @message like /Exception/| stats count(*) as errors by bin(5m) # Slowest Lambda invocationsfilter @type = "REPORT"| stats avg(@duration), max(@duration) by bin(5m)| sort max(@duration) descLogs 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.
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-alertsMilestone 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.
aws sns create-topic --name devops-monitoring-alertsaws 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 periodsaws 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 loadaws 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.
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-oncallEC2 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.
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:recoverFour 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.
# root-login-alert.yamlAWSTemplateFormatVersion: "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-securityConsole 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.
# audit-trail.yamlAWSTemplateFormatVersion: "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}/"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 dayaws cloudtrail lookup-events \ --lookup-attributes AttributeKey=EventName,AttributeValue=RevokeSecurityGroupIngress \ --max-results 5 \ --query "Events[].[EventTime,Username,EventName]" --output tableFor 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.
SecuritySend 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.
# 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 complianceaws 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 changedaws configservice get-resource-config-history \ --resource-type AWS::EC2::SecurityGroup --resource-id sg-0abc123def456789 --limit 5A 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
aws cloudwatch delete-alarms --alarm-names high-cpu-prod recover-web-1 prod-web-saturatedaws sns delete-topic --topic-arn arn:aws:sns:ap-south-1:123456789012:devops-monitoring-alertsaws 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 chargesProduction Best Practices & Common Pitfalls
- Set log retention on every log group. Never leave logs at "never expire" by accident.
- Alert on symptoms users feel. Error rate and latency matter more than CPU.
- Use composite alarms and M-of-N datapoints. They reduce pages for harmless spikes.
- Enable data events for sensitive S3 buckets. They are off by default.
- Protect the audit trail. Separate account, log file validation and restricted deletion.
- Alert on high-risk events. Root sign-ins, IAM policy changes and CloudTrail being stopped.
- Use Config for continuous detection with remediation. Use SCPs and IAM policies for prevention.
Common MistakeTreating 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.
RememberEC2 does not report memory by default, and CloudTrail does not log S3 object reads and writes by default. Both need explicit setup.
TipRun
aws cloudwatch set-alarm-stateafter 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 |