Skip to content

Instantly share code, notes, and snippets.

@acarapetis
Last active April 8, 2022 10:39
Show Gist options
  • Save acarapetis/3f545fcca29d940cfc829c76a9f66ac7 to your computer and use it in GitHub Desktop.
Save acarapetis/3f545fcca29d940cfc829c76a9f66ac7 to your computer and use it in GitHub Desktop.
Python script to assess EC2 Reserved Instance usage
#!/usr/bin/env python3
import boto3
from collections import defaultdict
ris = boto3.client("ec2").describe_reserved_instances()["ReservedInstances"]
ri_counts = defaultdict(lambda: 0)
for ri in ris:
if ri["State"] == "active":
ri_counts[ri["InstanceType"]] += ri["InstanceCount"]
instances = boto3.client("ec2").describe_instances(
Filters=[{"Name": "instance-state-name", "Values": ["running"]}]
)
inst_counts = defaultdict(lambda: 0)
for res in instances["Reservations"]:
for i in res["Instances"]:
inst_counts[i["InstanceType"]] += 1
MULTS = {
"micro": 1,
"small": 2,
"medium": 4,
"large": 8,
"xlarge": 16,
"2xlarge": 32,
"4xlarge": 64,
# TODO: fill in any more you need
}
def convert_to_micro(counts):
ret = defaultdict(lambda: 0)
for t, n in counts.items():
series, size = t.split(".")
ret[series] += MULTS[size] * n
return ret
reserved = convert_to_micro(ri_counts)
running = convert_to_micro(inst_counts)
print("Instance counts in .micro size equivalent:\n"
"Type | # Reserved | # Running\n"
"-----------------------------")
for t in running:
reserved[t] += 0 # ensure reserved.keys() includes running.keys()
for t in reserved:
print("% 4s | % 10d | % 9d" % (t, reserved[t], running[t]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment