We should learn EC2 Monitoring with CloudWatch and Automated Remediation to gain hands-on experience in detecting, visualizing, and resolving infrastructure issues in real time.
It helps build production-ready skills for proactive alerting, self-healing automation, and maintaining high availability in cloud environments.
β‘ Quick Reference
Keep the momentum going β everything you need on LearnXOps in one place:
- π Courses β Video courses & AI-built courses
- π Ebooks β Community ebooks & your own
- π§ͺ All Labs & Challenges β DevOps, Cloud, SRE & more
- βΈοΈ Kubernetes Labs & Playground β kind clusters, playground & challenges
- π€ AI Agent & Bot Labs β OpenClaw Β· Hermes Β· CrewAI Β· LangGraph Β· MCP
π§ Learn here
About this project:
It's a comprehensive AWS monitoring solution that demonstrates CloudWatch metrics, logs, dashboards, alarms, and automated remediation using Lambda functions.
This project uses Terraform as an Infra as Code tool to create the entire infrastructure in a few minutes!

π Learning Objectives
This project demonstrates:
-
CloudWatch Metrics:
- Standard vs custom metrics
- CloudWatch Agent installation and configuration
- Metric namespaces and dimensions
-
CloudWatch Logs:
- Log groups and streams
- Log collection from EC2
- Log retention policies
-
CloudWatch Dashboards:
- Widget types (line, number, log)
- Dashboard JSON structure
- Metric visualization
-
CloudWatch Alarms:
- Threshold-based alarms
- Evaluation periods and statistics
- Alarm actions (SNS, Lambda)
-
SNS Notifications:
- Topic creation and subscriptions
- Email notifications
- Integration with CloudWatch
-
Lambda Functions:
- Event-driven architecture
- CloudWatch alarm integration
- EC2 API operations
- Error handling and logging
- Cross-platform deployment (x86_64)
-
Infrastructure as Code:
- Terraform best practices
- Resource dependencies
- Output values
- Variable management
-
Automated Remediation:
- Self-healing infrastructure
- Cooldown periods
- Idempotent operations
Architecture

π Features
CloudWatch Metrics
- Standard EC2 Metrics: CPU, Network, Status Checks
- Custom Metrics via CloudWatch Agent:
- Memory utilization (%)
- Disk utilization (%)
- Disk I/O operations
- Network connections
- Swap usage
CloudWatch Alarms
- High CPU Alarm: Triggers when CPU > 80% for 10 minutes
- High Memory Alarm: Triggers when Memory > 80% for 10 minutes
- High Disk Alarm: Triggers when Disk > 85% for 10 minutes
- Status Check Failed: Triggers on instance or system check failures
CloudWatch Dashboard
- Real-time visualization of all metrics
- Historical trend analysis
- Single-value widgets for current status
- Log insights integration
Automated Remediation
- Lambda Function automatically responds to alarms
- Reboot Instance: On high CPU or memory issues
- Cooldown Period: Prevents repeated actions (30 minutes)
- SNS Notifications: Sends detailed remediation reports
- Error Handling: Graceful failure with notifications
CloudWatch Logs
- System and security logs (
/var/log/messagesand/var/log/securein the agent config; on the Ubuntu AMI the equivalents are/var/log/syslogand/var/log/auth.log) - Custom application logs
- 7-day retention policy
Now let's deploy it
Prerequisites
- AWS Account with appropriate permissions
- AWS CLI configured with credentials
- Terraform >= 1.0
- Python 3.11+ and pip3
- macOS (scripts optimized for Mac, but work on Linux too)
π Project Structure
.
βββ main.tf # Main Terraform configuration
βββ variables.tf # Input variables
βββ outputs.tf # Output values
βββ terraform.tfvars.example # Example configuration
βββ Makefile # Make targets for common tasks
βββ .gitignore # Git ignore rules
β
βββ lambda/
β βββ lambda_function.py # Auto-remediation Lambda (Python 3.11)
β βββ requirements.txt # Python dependencies
β
βββ scripts/
β βββ deploy.sh # Automated deployment script
β βββ destroy.sh # Cleanup script
β βββ build_lambda.sh # Build Lambda package for x86_64
β βββ user_data.sh # EC2 initialization script
β βββ test_cpu_stress.sh # CPU stress test script
β βββ test_memory_stress.sh # Memory stress test script
β
βββ configs/
βββ cloudwatch-config.json # CloudWatch Agent configuration
βββ dashboard.json # Dashboard template
Installation
-
Clone project:
git clone https://github.com/sd031/ec2-monitoing-auto-remediation-terraform-lambda.git cd ec2-monitoing-auto-remediation-terraform-lambda -
Configure your settings:
cp terraform.tfvars.example terraform.tfvars nano terraform.tfvarsUpdate with your email and preferences:
aws_region = "us-east-1" project_name = "ec2-monitoring" instance_type = "t3.micro" alarm_email = "[email protected]" # REQUIRED cpu_threshold = 80 memory_threshold = 80 disk_threshold = 85 -
Deploy the infrastructure:
# Using the deploy script (recommended) chmod +x scripts/deploy.sh ./scripts/deploy.sh # Or using Make make deploy -
Confirm SNS subscription:
- Check your email for SNS subscription confirmation
- Click the confirmation link
-
Wait for metrics (5-10 minutes):
- CloudWatch Agent needs time to start reporting
- Check the dashboard after this period
π Using the Dashboard
Access your CloudWatch Dashboard:
# Get the dashboard URL
terraform output dashboard_url
# Or open directly
open "https://console.aws.amazon.com/cloudwatch/home?region=us-east-1#dashboards:name=ec2-monitoring-dashboard"
The dashboard includes:
- CPU Utilization: Average and maximum over time
- Memory Utilization: Percentage used
- Disk Utilization: Percentage used per mount point
- Network Traffic: In/out bytes
- Disk I/O: Read/write operations
- Status Checks: Instance and system health
- Recent Logs: Last 100 log entries
- Current Values: Single-value widgets for quick status
π§ͺ Testing the Monitoring
Test CPU Alarm
Open a shell on the instance and run:
# Using SSM Session Manager (no SSH key needed)
aws ssm start-session --target $(terraform output -raw instance_id)
# Run CPU stress test
sudo stress --cpu $(nproc) --timeout 300s
Or use the provided script:
# The instance has no SSH key pair: in the Session Manager shell,
# paste the contents of scripts/test_cpu_stress.sh, then press Ctrl-D
cat > test_cpu_stress.sh
chmod +x test_cpu_stress.sh
./test_cpu_stress.sh
Test Memory Alarm
# On the EC2 instance
sudo stress --vm 1 --vm-bytes 512M --timeout 300s
Or use the provided script:
# In the Session Manager shell: paste the contents of
# scripts/test_memory_stress.sh, then press Ctrl-D
cat > test_memory_stress.sh
chmod +x test_memory_stress.sh
./test_memory_stress.sh
Expected Behavior
- After 2 evaluation periods (10 minutes), the alarm triggers
- SNS notification sent to your email
- Lambda function executes automatically
- Instance reboots (if configured action)
- Second notification sent with remediation details
- Cooldown period prevents repeated actions for 30 minutes
π§ Configuration
Adjusting Thresholds
Edit terraform.tfvars:
cpu_threshold = 90 # Increase to 90%
memory_threshold = 85 # Increase to 85%
disk_threshold = 90 # Increase to 90%
Then apply changes:
terraform apply
Modifying Remediation Actions
Edit lambda/lambda_function.py:
REMEDIATION_ACTIONS = {
'high-cpu': 'reboot', # Change to 'stop' or add custom action
'high-memory': 'reboot',
'status-check-failed': 'reboot',
}
Rebuild and redeploy:
make build
terraform apply
Changing Cooldown Period
Edit lambda/lambda_function.py:
COOLDOWN_PERIOD = 60 # Change to 60 minutes
π Troubleshooting
CloudWatch Agent Not Reporting Metrics
# Open a shell on the instance
aws ssm start-session --target <instance-id>
# Check agent status
sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl \
-a query -m ec2 -c default -s
# View agent logs
sudo tail -f /opt/aws/amazon-cloudwatch-agent/logs/amazon-cloudwatch-agent.log
Lambda Function Not Triggering
-
Check Lambda logs:
aws logs tail /aws/lambda/ec2-monitoring-auto-remediation --follow -
Verify Lambda permissions:
aws lambda get-policy --function-name ec2-monitoring-auto-remediation -
Test Lambda manually (create
test-event.jsonwith a sample alarm event first; the repo doesn't include one):aws lambda invoke \ --function-name ec2-monitoring-auto-remediation \ --cli-binary-format raw-in-base64-out \ --payload file://test-event.json \ response.json
Alarms Not Triggering
-
Check alarm state:
aws cloudwatch describe-alarms \ --alarm-names ec2-monitoring-high-cpu -
Verify metrics are being reported:
# GNU date (Linux). On macOS use: date -u -v-1H +%Y-%m-%dT%H:%M:%S aws cloudwatch get-metric-statistics \ --namespace CWAgent \ --metric-name mem_used_percent \ --dimensions Name=InstanceId,Value=<instance-id> \ --start-time $(date -u -d '1 hour ago' +%Y-%m-%dT%H:%M:%S) \ --end-time $(date -u +%Y-%m-%dT%H:%M:%S) \ --period 300 \ --statistics Average
SNS Subscription Not Confirmed
-
Check SNS subscriptions:
aws sns list-subscriptions-by-topic \ --topic-arn $(terraform output -raw sns_topic_arn) -
Resend confirmation:
aws sns subscribe \ --topic-arn $(terraform output -raw sns_topic_arn) \ --protocol email \ --notification-endpoint [email protected]
π§Ή Cleanup
To destroy all resources:
# Using the destroy script
./scripts/destroy.sh
# Or using Make
make destroy
# Or using Terraform directly
terraform destroy
This will remove:
- EC2 instance
- VPC and networking
- CloudWatch alarms and dashboard
- SNS topic
- Lambda function
- IAM roles and policies
- CloudWatch log groups
Challenges
- Multi-Region High Availability - Deploy infrastructure across multiple AWS regions with automatic failover
- Advanced Auto-Remediation with ML - Use CloudWatch Anomaly Detection and intelligent graduated responses instead of just restarting instances
- Cost Optimization & Auto-Scaling - Add cost monitoring, metric-based auto-scaling, and automated right-sizing recommendations
- Security & Compliance Monitoring - Integrate GuardDuty, VPC Flow Logs, AWS Config rules, and automated security patching
- Application Performance Monitoring (APM) - Add X-Ray tracing, custom application metrics, synthetic monitoring, and service-level objectives (SLOs)
π€·π» How to Participate?
β
Complete the tasks and challenges.
β
Document your progress and key takeaways on GitHub ReadMe, Medium, or Hashnode.
β
Share the above in a LinkedIn post tagging me (Sandip Das), and use #90DaysOfCloud to engage with the community!
β‘ Quick Reference
Keep the momentum going β everything you need on LearnXOps in one place:
- π Courses β Video courses & AI-built courses
- π Ebooks β Community ebooks & your own
- π§ͺ All Labs & Challenges β DevOps, Cloud, SRE & more
- βΈοΈ Kubernetes Labs & Playground β kind clusters, playground & challenges
- π€ AI Agent & Bot Labs β OpenClaw Β· Hermes Β· CrewAI Β· LangGraph Β· MCP

Member discussion