Write a script that sorts EC2 instances by monthly cost estimate using a price map.
IntermediateHands-onPython for DevOps
Answer
import boto3
from collections import defaultdict
HOURLY = {"t3.micro": 0.0104, "t3.medium": 0.0416, "m5.large": 0.096} # sample on-demand prices
ec2 = boto3.client("ec2")
cost = defaultdict(float)
for page in ec2.get_paginator("describe_instances").paginate(
Filters=[{"Name": "instance-state-name", "Values": ["running"]}]):
for r in page["Reservations"]:
for i in r["Instances"]:
team = next((t["Value"] for t in i.get("Tags", []) if t["Key"] == "team"), "untagged")
cost[team] += HOURLY.get(i["InstanceType"], 0) * 730
for team, c in sorted(cost.items(), key=lambda kv: kv[1], reverse=True):
print(f"{team:15} ${c:,.2f}/month")
Key trick → 730 is the average number of hours in a month. Grouping by a team tag shows who owns the spend. For real numbers, use Cost Explorer (ce.get_cost_and_usage) grouped by tag.
More on Python for DevOps
Write a Python script using boto3 that lists all running EC2 instances with their Name tag.BeginnerWrite a script that finds unattached EBS volumes and deletes them (with a dry-run flag).IntermediateCall a REST API with `requests`, handle timeouts and non-2xx responses properly.BeginnerAdd retry with exponential backoff to HTTP calls without writing the loop yourself.IntermediateWrite your own retry decorator with exponential backoff and jitter.AdvancedParse a YAML file and print every container image in a multi-document Kubernetes manifest.Intermediate