Created
July 8, 2026 08:58
-
-
Save Dirga36/0d1a6861e27bc7f3834ca65d5ec1a561 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import boto3 | |
| from datetime import datetime, timedelta | |
| def find_idle_instances(cpu_threshold=5.0, days=7): | |
| ec2 = boto3.client("ec2") | |
| cloudwatch = boto3.client("cloudwatch") | |
| idle_instances = [] | |
| instances = ec2.describe_instances( | |
| Filters=[{"Name": "instance-state-name", "Values": ["running"]}] | |
| ) | |
| for reservation in instances["Reservations"]: | |
| for instance in reservation["Instances"]: | |
| instance_id = instance["InstanceId"] | |
| metrics = cloudwatch.get_metric_statistics( | |
| Namespace="AWS/EC2", | |
| MetricName="CPUUtilization", | |
| Dimensions=[{"Name": "InstanceId", "Value": instance_id}], | |
| StartTime=datetime.utcnow() - timedelta(days=days), | |
| EndTime=datetime.utcnow(), | |
| Period=86400, | |
| Statistics=["Average"], | |
| ) | |
| if not metrics["Datapoints"]: | |
| continue | |
| avg_cpu = sum(dp["Average"] for dp in metrics["Datapoints"]) / len( | |
| metrics["Datapoints"] | |
| ) | |
| if avg_cpu < cpu_threshold: | |
| idle_instances.append((instance_id, round(avg_cpu, 2))) | |
| return idle_instances |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment