πŸ’‘
Hey β€” It's Sandip Das πŸ‘‹

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:


πŸ‘£
60 Days of DevOps (Complete)
30 Days of MLOps (Complete)
90 Days of Cloud (in progress)

🧠 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:

  1. CloudWatch Metrics:

    • Standard vs custom metrics
    • CloudWatch Agent installation and configuration
    • Metric namespaces and dimensions
  2. CloudWatch Logs:

    • Log groups and streams
    • Log collection from EC2
    • Log retention policies
  3. CloudWatch Dashboards:

    • Widget types (line, number, log)
    • Dashboard JSON structure
    • Metric visualization
  4. CloudWatch Alarms:

    • Threshold-based alarms
    • Evaluation periods and statistics
    • Alarm actions (SNS, Lambda)
  5. SNS Notifications:

    • Topic creation and subscriptions
    • Email notifications
    • Integration with CloudWatch
  6. Lambda Functions:

    • Event-driven architecture
    • CloudWatch alarm integration
    • EC2 API operations
    • Error handling and logging
    • Cross-platform deployment (x86_64)
  7. Infrastructure as Code:

    • Terraform best practices
    • Resource dependencies
    • Output values
    • Variable management
  8. Automated Remediation:

    • Self-healing infrastructure
    • Cooldown periods
    • Idempotent operations

Architecture

EC2 monitoring: the CloudWatch agent sends metrics and logs, four alarms notify an SNS topic, and three of them invoke a remediation Lambda that reboots the instance with a 30-minute cooldown

πŸ“‹ 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/messages and /var/log/secure in the agent config; on the Ubuntu AMI the equivalents are /var/log/syslog and /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

  1. Clone project:

    git clone https://github.com/sd031/ec2-monitoing-auto-remediation-terraform-lambda.git
    cd ec2-monitoing-auto-remediation-terraform-lambda
    
  2. Configure your settings:

    cp terraform.tfvars.example terraform.tfvars
    nano terraform.tfvars
    

    Update 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
    
  3. Deploy the infrastructure:

    # Using the deploy script (recommended)
    chmod +x scripts/deploy.sh
    ./scripts/deploy.sh
    
    # Or using Make
    make deploy
    
  4. Confirm SNS subscription:

    • Check your email for SNS subscription confirmation
    • Click the confirmation link
  5. 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

  1. After 2 evaluation periods (10 minutes), the alarm triggers
  2. SNS notification sent to your email
  3. Lambda function executes automatically
  4. Instance reboots (if configured action)
  5. Second notification sent with remediation details
  6. 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

  1. Check Lambda logs:

    aws logs tail /aws/lambda/ec2-monitoring-auto-remediation --follow
    
  2. Verify Lambda permissions:

    aws lambda get-policy --function-name ec2-monitoring-auto-remediation
    
  3. Test Lambda manually (create test-event.json with 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

  1. Check alarm state:

    aws cloudwatch describe-alarms \
        --alarm-names ec2-monitoring-high-cpu
    
  2. 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

  1. Check SNS subscriptions:

    aws sns list-subscriptions-by-topic \
        --topic-arn $(terraform output -raw sns_topic_arn)
    
  2. 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:

Share this post