Automated cost-saving architecture on AWS that reduced monthly infrastructure expenses by 20%
Rising AWS costs in non-production environments due to:
An intelligent, serverless system that automatically manages AWS resource states based on predefined schedules and budget thresholds.
```mermaid graph LR A[EventBridge Rule] –>|Scheduled Trigger| B[Lambda Function] C[CloudWatch Alarms] –>|Budget Alert| B B –>|boto3| D[EC2 Instances] B –>|Logs| E[CloudWatch Logs] F[Terraform] –>|Provisions| A F –>|Provisions| B F –>|Provisions| C
style B fill:#FF9900
style F fill:#7B42BC
style D fill:#FF9900 \`\`\`
``` infrastructure-cost-optimization/ ├── src/ │ └── budget_police/ │ └── lambda_function.py # Main Lambda handler └── terraform/ └── modules/ └── scheduler/ └── main.tf # Infrastructure as Code ```
Clone the repository ```bash git clone https://github.com/Abhinandansinha01/portfolio.git cd infrastructure-cost-optimization ```
Configure Terraform variables ```bash cd terraform/modules/scheduler
```
Deploy infrastructure ```bash terraform init terraform plan terraform apply ```
Tag your EC2 instances ```bash
aws ec2 create-tags –resources i-1234567890abcdef0
–tags Key=AutoStop,Value=true Key=Environment,Value=dev
```
| Variable | Description | Example |
|---|---|---|
SCHEDULE_TAG |
Tag key to identify managed instances | AutoStop |
ENVIRONMENT_TAG |
Environment filter | dev,staging |
STOP_TIME |
Time to stop instances (UTC) | 18:00 |
START_TIME |
Time to start instances (UTC) | 08:00 |
Edit the cron expression in main.tf:
```hcl
schedule_expression = “cron(0 18 ? MON-FRI)” # Stop at 6 PM weekdays
```
| Metric | Before | After | Improvement |
|---|---|---|---|
| Monthly EC2 Costs | $500 | $400 | 20% reduction |
| Idle Instance Hours | 720 hrs/month | 240 hrs/month | 67% reduction |
| Manual Interventions | 15/month | 0 | 100% automation |
For a t3.medium instance ($0.0416/hour):
The lambda_function.py implements:
```python def lambda_handler(event, context): # 1. Get current time and action (start/stop) # 2. Query EC2 instances with AutoStop tag # 3. Filter by environment (dev, staging) # 4. Execute stop/start action # 5. Log results to CloudWatch # 6. Send SNS notification (optional) ```
The Lambda function needs:
```json { “Version”: “2012-10-17”, “Statement”: [ { “Effect”: “Allow”, “Action”: [ “ec2:DescribeInstances”, “ec2:StopInstances”, “ec2:StartInstances”, “ec2:DescribeTags” ], “Resource”: “” }, { “Effect”: “Allow”, “Action”: [ “logs:CreateLogGroup”, “logs:CreateLogStream”, “logs:PutLogEvents” ], “Resource”: “arn:aws:logs:::” } ] } ```
Configure SNS topic for:
Contributions are welcome! Please feel free to submit a Pull Request.
This project is open source and available under the MIT License.
Abhinandan Sinha