#!/usr/bin/env python3 """AWS bill audit: read a billing export, write a ranked savings memo as one HTML file. Reads Cost and Usage Report 2.0 (CSV), legacy CUR (CSV), FOCUS 1.x from AWS Data Exports (CSV), and Cost Explorer CSV downloads grouped by usage type. Files may be .csv, .csv.gz, .zip, .parquet (Parquet needs pyarrow) or a folder of them. Nothing leaves the machine: the script reads local files and rates.json (AWS public list prices, built by fetch_rates.py). python3 audit.py BILL [BILL ...] -o memo.html --company "Name" [--fee 1000 [--fee-label "₹85,000"]] [--sample] """ import argparse, csv, datetime as dt, gzip, html, io, json, math, os, re, sys, zipfile from collections import Counter, defaultdict HERE = os.path.dirname(os.path.abspath(__file__)) csv.field_size_limit(min(sys.maxsize, 2**31 - 1)) USAGE_LT = {"Usage", "SavingsPlanCoveredUsage", "DiscountedUsage"} DISCOUNT_LT = {"EdpDiscount", "PrivateRateDiscount", "BundledDiscount", "SppDiscount", "DistributorDiscount", "Discount"} NONPROD = {"dev", "development", "staging", "stage", "test", "testing", "qa", "uat", "sandbox", "demo"} ENV_KEYS = {"env", "environment", "stage"} # AWS's list of previous-generation instance families (docs.aws.amazon.com/ec2/latest/instancetypes/pg.html) PREV_GEN = {"a1", "c1", "c3", "c4", "g3", "i2", "m1", "m2", "m3", "m4", "p3dn", "r3", "r4", "t1"} TARGETS = { # same size, cheapest current generation: (x86 candidates, Graviton candidates) "m": (["m5", "m6i", "m6a", "m7i", "m7a"], ["m6g", "m7g", "m8g"]), "c": (["c5", "c6i", "c6a", "c7i", "c7a"], ["c6g", "c7g", "c8g"]), "r": (["r5", "r6i", "r6a", "r7i", "r7a"], ["r6g", "r7g", "r8g"]), "i": (["i3", "i4i"], ["i4g"]), "t": (["t3", "t3a"], ["t4g"]), } # RDS major versions: the Year 3 Extended Support price (double Year 1-2) starts on these dates. # Sources: RDS for MySQL and PostgreSQL release calendars, Aurora MySQL release calendar (read 20 Nov 2026). YEAR3 = {"MySQL5.7": "2026-03-01", "MySQL8.0": "2028-08-01", "PostgreSQL11": "2026-04-01", "PostgreSQL12": "2027-03-01", "PostgreSQL13": "2028-03-01", "AuroraMySQL2": "2026-12-01"} ES_TARGET = {"MySQL": "MySQL 8.4 (standard support to 31 July 2029)", "PostgreSQL": "PostgreSQL 17 (standard support to 28 February 2030)", "AuroraMySQL": "Aurora MySQL version 3 (standard support to 30 April 2028)", "AuroraPostgreSQL": "a current Aurora PostgreSQL major version"} # OpenSearch Service: from 7 Nov 2026 Extended Support on Elasticsearch 1.5-7.8 (not 5.6), OpenSearch 1.0-1.2 and 2.3-2.9 is charged # at the instance price (usage type EnhancedOSExtendedSupport:), instead of a flat rate per normalized instance-hour # (OpenSearchExtendedSupport, $0.0065 in us-east-1; 5.6 keeps it to 7 Nov 2028). Sources (read 23 Nov 2026): # docs.aws.amazon.com/opensearch-service/latest/developerguide/what-is.html#end-of-support, aws.amazon.com/opensearch-service/pricing/, # AmazonES price list us-east-1 (version 20261116205525: every EnhancedOSExtendedSupport rate equals its ESInstance rate). OS_DOUBLED = dt.datetime(2026, 11, 7) OS_MIN_RATIO = 4.34 # the smallest new/old step in that price list (c6g.*: $0.113 an hour vs $0.0065 x 4 NIH for a large) # ElastiCache for Redis OSS Extended Support: 80% of the On-Demand node price in Years 1-2, 160% in Year 3; reserved nodes don't # discount it. v4/v5 from 1 Feb 2026 (Year 3 from 1 Feb 2028); v6 from 1 Feb 2027 (standard support ends 31 Jan 2027). # Valkey nodes are priced 20% below Redis OSS. Sources (read 23 Nov 2026): docs.aws.amazon.com/AmazonElastiCache/latest/dg/ # extended-support-versions.html and extended-support-charges.html, aws.amazon.com/elasticache/pricing/, AmazonElastiCache price list # us-east-1 (version 20261118174528: ExtendedSupportYr1_Yr2-NodeUsage = 80% of NodeUsage, Valkey NodeUsage = 80% of Redis). EC_V6_START, EC_V45_YEAR3 = dt.datetime(2027, 2, 1), dt.datetime(2028, 2, 1) VALKEY_CUT = 0.20 # Usage-type prefixes of the commercial regions, as the AWSDataTransfer price list pairs them with region codes (read 20 Nov 2026). PFX = {"USE1": "us-east-1", "USE2": "us-east-2", "USW1": "us-west-1", "USW2": "us-west-2", "CAN1": "ca-central-1", "CAN2": "ca-west-1", "MXC1": "mx-central-1", "SAE1": "sa-east-1", "EU": "eu-west-1", "EUW2": "eu-west-2", "EUW3": "eu-west-3", "EUC1": "eu-central-1", "EUC2": "eu-central-2", "EUN1": "eu-north-1", "EUS1": "eu-south-1", "EUS2": "eu-south-2", "ILC1": "il-central-1", "MEC1": "me-central-1", "MES1": "me-south-1", "AFS1": "af-south-1", "APN1": "ap-northeast-1", "APN2": "ap-northeast-2", "APN3": "ap-northeast-3", "APE1": "ap-east-1", "APE2": "ap-east-2", "APS1": "ap-southeast-1", "APS2": "ap-southeast-2", "APS3": "ap-south-1", "APS4": "ap-southeast-3", "APS5": "ap-south-2", "APS6": "ap-southeast-4", "APS7": "ap-southeast-5", "APS8": "ap-southeast-6", "APS9": "ap-southeast-7"} PFX_RE = re.compile(r"^([A-Z]{2,4}\d?)-(.+)$") SERVICE_NAMES = { "AmazonEC2": "EC2, EBS and NAT gateways", "AmazonRDS": "RDS", "AmazonS3": "S3", "AmazonCloudWatch": "CloudWatch", "AWSDataTransfer": "Data transfer", "AmazonVPC": "VPC (public IPv4, endpoints)", "AWSELB": "Elastic Load Balancing", "AmazonEKS": "EKS", "AmazonElastiCache": "ElastiCache", "AmazonDynamoDB": "DynamoDB", "AWSLambda": "Lambda", "AmazonES": "OpenSearch Service", "AmazonECR": "ECR", "AWSQueueService": "SQS", "AWSSecretsManager": "Secrets Manager", "AmazonCloudFront": "CloudFront", "ComputeSavingsPlans": "Savings Plans", } # ---------------------------------------------------------------- reading def fnum(x): if x is None or x == "": return None try: return float(x) except ValueError: return None def parse_dt(s): if not s: return None s = s.strip().replace("T", " ") for fmt, n in (("%Y-%m-%d %H:%M:%S", 19), ("%Y-%m-%d %H:%M", 16), ("%Y-%m-%d", 10)): try: return dt.datetime.strptime(s[:n], fmt) except ValueError: continue return None def split_ut(ut): m = PFX_RE.match(ut or "") if m and (m.group(1) in PFX or re.match(r"^[A-Z]{3}\d$", m.group(1))): # An unknown region prefix is kept as a marker, so it is flagged rather than taken for us-east-1. return PFX.get(m.group(1), "prefix:" + m.group(1)), m.group(2) return None, ut or "" def parse_map(s): if not s or s in ("{}", "null"): return {} try: v = json.loads(s) return v if isinstance(v, dict) else {} except ValueError: return {} def snake(name): return re.sub(r"(?<=[a-z0-9])([A-Z])", r"_\1", name.replace("/", "_")).lower() def infer_product(ut): u = ut if u.startswith(("BoxUsage", "SpotUsage", "DedicatedUsage", "HostUsage", "EBS:", "NatGateway", "ElasticIP:", "CPUCredits")): return "AmazonEC2" if "NodeUsage:cache." in u: # ElastiCache nodes, and their Extended Support (ExtendedSupportYr1_Yr2-NodeUsage:cache.m5.large) return "AmazonElastiCache" if u.startswith(("InstanceUsage:db", "Multi-AZUsage:db", "RDS:", "Aurora:")) or (u.startswith("ExtendedSupport:") and "EKS" not in u): return "AmazonRDS" if u.startswith("AmazonEKS"): return "AmazonEKS" if u.startswith(("PublicIPv4", "VpcEndpoint")): return "AmazonVPC" if "OpenSearch" in u or u.startswith(("ESInstance", "EnhancedOSExtendedSupport")): return "AmazonES" if u.startswith("DataTransfer-") or "-AWS-Out-Bytes" in u or "-AWS-In-Bytes" in u: return "AWSDataTransfer" if u.startswith(("LoadBalancerUsage", "LCUUsage")): return "AWSELB" if u.startswith(("TimedStorage", "Requests-Tier")): return "AmazonS3" if u.startswith(("DataProcessing", "VendedLog", "CW:")): return "AmazonCloudWatch" return "Unknown" def user_tags(m): out = {} for k, v in m.items(): if not v: continue if k.startswith(("user_", "user:")): out[k[5:]] = v elif not k.startswith(("aws_", "aws:")): out[k] = v return out def rows_cur2(r): prod = parse_map(r.get("product")) if (not r.get("product_region_code") or not r.get("product_instance_type")) else {} return dict(start=r.get("line_item_usage_start_date"), end=r.get("line_item_usage_end_date"), product=r.get("line_item_product_code") or "", ut=r.get("line_item_usage_type") or "", op=r.get("line_item_operation") or "", rid=r.get("line_item_resource_id") or "", amount=fnum(r.get("line_item_usage_amount")), unit=r.get("pricing_unit") or "", cost=fnum(r.get("line_item_unblended_cost")) or 0.0, od_cost=fnum(r.get("pricing_public_on_demand_cost")), od_rate=fnum(r.get("pricing_public_on_demand_rate")), ltype=r.get("line_item_line_item_type") or "Usage", term=r.get("pricing_term") or "", region=r.get("product_region_code") or prod.get("region") or "", az=r.get("line_item_availability_zone") or "", itype=r.get("product_instance_type") or prod.get("instance_type") or "", desc=r.get("line_item_line_item_description") or "", account=r.get("line_item_usage_account_id") or "", tags=user_tags(parse_map(r.get("resource_tags"))), currency=r.get("line_item_currency_code") or "USD", tagcol="resource_tags" in r) def rows_cur1(r, tagcols): g = lambda k: r.get(k) or "" return dict(start=g("lineItem/UsageStartDate"), end=g("lineItem/UsageEndDate"), product=g("lineItem/ProductCode"), ut=g("lineItem/UsageType"), op=g("lineItem/Operation"), rid=g("lineItem/ResourceId"), amount=fnum(g("lineItem/UsageAmount")), unit=g("pricing/unit"), cost=fnum(g("lineItem/UnblendedCost")) or 0.0, od_cost=fnum(g("pricing/publicOnDemandCost")), od_rate=fnum(g("pricing/publicOnDemandRate")), ltype=g("lineItem/LineItemType") or "Usage", term=g("pricing/term"), region=g("product/regionCode") or g("product/region"), az=g("lineItem/AvailabilityZone"), itype=g("product/instanceType"), desc=g("lineItem/LineItemDescription"), account=g("lineItem/UsageAccountId"), tags={c.split(":", 1)[1]: r[c] for c in tagcols if r.get(c)}, currency=g("lineItem/CurrencyCode") or "USD", tagcol=bool(tagcols)) def rows_focus(r): cat = r.get("ChargeCategory") or "Usage" lt = {"Usage": "Usage", "Purchase": "Fee", "Tax": "Tax", "Credit": "Credit", "Adjustment": "Refund"}.get(cat, cat) if lt == "Usage" and r.get("CommitmentDiscountId"): lt = "SavingsPlanCoveredUsage" term = {"Standard": "OnDemand", "Committed": "Committed", "Dynamic": "Spot"}.get(r.get("PricingCategory") or "", "") ut = r.get("x_UsageType") or r.get("SkuId") or "" return dict(start=r.get("ChargePeriodStart"), end=r.get("ChargePeriodEnd"), product=r.get("x_ServiceCode") or r.get("ServiceName") or infer_product(split_ut(ut)[1]), ut=ut, op=r.get("x_Operation") or "", rid=r.get("ResourceId") or "", amount=fnum(r.get("ConsumedQuantity")), unit=r.get("ConsumedUnit") or r.get("PricingUnit") or "", cost=fnum(r.get("BilledCost")) or 0.0, od_cost=fnum(r.get("ListCost")), od_rate=fnum(r.get("ListUnitPrice")), ltype=lt, term=term, region=r.get("RegionId") or "", az=r.get("AvailabilityZone") or "", itype="", desc=r.get("ChargeDescription") or "", account=r.get("SubAccountId") or "", tags=user_tags(parse_map(r.get("Tags"))), currency=r.get("BillingCurrency") or "USD", tagcol="Tags" in r) def parquet_cell(v): """Parquet map columns (CUR 2.0 product, resource_tags) come back as lists of (key, value) pairs.""" if v is None: return "" if isinstance(v, list) and all(isinstance(x, tuple) and len(x) == 2 for x in v): v = dict(v) if isinstance(v, (dict, list)): return json.dumps(v, default=str) return v def open_texts(path): """Yield (name, text stream) for every CSV inside path (file, .gz, .zip or folder).""" if os.path.isdir(path): for root, _, files in os.walk(path): for f in sorted(files): if re.search(r"\.(csv|csv\.gz|zip|parquet)$", f, re.I): yield from open_texts(os.path.join(root, f)) return low = path.lower() if low.endswith(".zip"): with zipfile.ZipFile(path) as z: for n in z.namelist(): if re.search(r"\.csv(\.gz)?$", n, re.I): raw = z.open(n) if n.lower().endswith(".gz"): raw = gzip.open(raw) yield n, io.TextIOWrapper(raw, encoding="utf-8-sig", newline="") return if low.endswith(".parquet"): try: import pyarrow.parquet as pq except ImportError: sys.exit(f"{path}: reading Parquet needs pyarrow (pip install pyarrow), or export the report as CSV") t = pq.read_table(path) buf = io.StringIO() w = csv.writer(buf) w.writerow(t.column_names) for batch in t.to_batches(): cols = [c.to_pylist() for c in batch.columns] for row in zip(*cols): w.writerow([parquet_cell(v) for v in row]) buf.seek(0) yield os.path.basename(path), buf return f = gzip.open(path, "rt", encoding="utf-8-sig", newline="") if low.endswith(".gz") else open(path, encoding="utf-8-sig", newline="") yield os.path.basename(path), f def read_rows(path): """Yield (format, row dict) for every line item in a bill export.""" for name, f in open_texts(path): try: rd = csv.reader(f) try: header = next(rd) except StopIteration: continue h = [x.strip() for x in header] if "line_item_usage_type" in h: fmt = "Cost and Usage Report 2.0" for vals in rd: yield fmt, name, rows_cur2(dict(zip(h, vals))) elif "lineItem/UsageType" in h: fmt = "Cost and Usage Report (legacy)" tagcols = [c for c in h if c.startswith("resourceTags/user:")] for vals in rd: yield fmt, name, rows_cur1(dict(zip(h, vals)), tagcols) elif "BilledCost" in h and "ChargePeriodStart" in h: fmt = "FOCUS" for vals in rd: yield fmt, name, rows_focus(dict(zip(h, vals))) elif len(h) > 1 and (h[0].lower() in CE_DIMS or sum(x.endswith("($)") for x in h[1:]) >= max(1, (len(h) - 1) // 2)): fmt = "Cost Explorer CSV (" + h[0] + ")" yield from ce_rows(fmt, name, h, list(rd)) else: print(f"warning: {name}: not a format this tool reads (header starts {h[:4]})", file=sys.stderr) finally: f.close() CE_DIMS = {"service", "usage type", "usagetype", "usage type group", "linked account", "region", "instance type", "api operation", "resource", "purchase option", "charge type"} def ce_rows(fmt, name, h, data): """Cost Explorer downloads come with dates as rows (groups as columns) or dates as columns (groups as rows).""" by_usage = "usage" in h[0].lower() def clean(g): g = g.strip() return g[:-3].strip() if g.endswith("($)") else g def emit(day, group, v): c = fnum(v.replace(",", "").replace("$", "")) if v else None g = clean(group) if not c or not g or g.lower().startswith(("total", "no ")) or g.lower().endswith("total"): return None reg, ut = split_ut(g) return dict(start=day.strftime("%Y-%m-%d %H:%M:%S"), end=None, product=infer_product(ut) if by_usage else g, ut=g if by_usage else "", op="", rid="", amount=None, unit="", cost=c, od_cost=None, od_rate=None, ltype="Usage", term="", region=reg or "us-east-1", az="", itype=ut.split(":", 1)[1] if ut.startswith("BoxUsage:") else "", desc="", account="", tags={}, currency="USD") if any(parse_dt(r[0]) for r in data if r): for vals in data: day = parse_dt(vals[0]) if vals else None if day: for g, v in zip(h[1:], vals[1:]): r = emit(day, g, v) if r: yield fmt, name, r else: days = [parse_dt(clean(x)) for x in h[1:]] for vals in data: if not vals: continue for day, v in zip(days, vals[1:]): r = emit(day, vals[0], v) if day else None if r: yield fmt, name, r # ---------------------------------------------------------------- aggregation class Item: __slots__ = ("product", "ut", "ut_raw", "op", "rid", "region", "az", "itype", "unit", "desc", "ltype", "term", "cost", "od_cost", "amount", "n", "first", "last", "tags", "rate") def __init__(self, r, ut): self.product, self.ut, self.ut_raw, self.op, self.rid = r["product"], ut, r["ut"], r["op"], r["rid"] self.region, self.az, self.itype, self.unit, self.desc = r["region"], r["az"], r["itype"], r["unit"], r["desc"] self.ltype, self.term, self.tags, self.rate = r["ltype"], r["term"], r["tags"], r["od_rate"] self.cost = self.od_cost = self.amount = 0.0 self.n, self.first, self.last = 0, None, None def hours(self): if self.first and self.last: return max(1.0, (self.last - self.first).total_seconds() / 3600) return None def name(self): t = self.tags or {} nm = t.get("Name") or t.get("name") rid = short_rid(self.rid) if nm and nm not in rid: return f"{nm} ({rid})" if rid else nm return rid or "(no resource ID)" def short_rid(rid): if not rid: return "" if rid.startswith("arn:"): parts = rid.split(":", 5) rest = parts[5] if len(parts) > 5 else rid rest = re.sub(r"^log-group:", "", rest) rest = re.sub(r"^loadbalancer/(app|net)/([^/]+)/.*$", r"\1/\2", rest) rest = re.sub(r"^loadbalancer/", "", rest) rest = re.sub(r"^(snapshot|volume|natgateway|elastic-ip)/", "", rest) return rest return rid class Bill: def __init__(self): self.items, self.svc = {}, defaultdict(float) self.by_lt = defaultdict(float) self.rows, self.formats, self.files = 0, Counter(), Counter() self.start = self.end = None self.durations = Counter() self.ce_days = set() # distinct dates on Cost Explorer rows, to tell daily from monthly downloads self.compute = defaultdict(float) # (period key, instance type, non-prod, region) -> On-Demand cost, Linux EC2 self.tag_cols = False # the export has a tag column at all (buyers may delete them) self.compute_covered = 0.0 self.compute_other_os = 0.0 self.untagged, self.tag_seen, self.usage_cost = defaultdict(float), False, 0.0 self.accounts, self.regions, self.currency = set(), Counter(), Counter() def add(self, fmt, fname, r): self.rows += 1 self.formats[fmt] += 1 self.files[fname] += 1 lt, cost = r["ltype"], r["cost"] self.by_lt[lt] += cost if lt not in ("Credit", "Refund", "Tax"): self.svc[r["product"] or "Unknown"] += cost self.currency[r["currency"]] += 1 if r["account"]: self.accounts.add(r["account"]) if r.get("tagcol"): self.tag_cols = True if lt not in USAGE_LT: return s, e = parse_dt(r["start"]), parse_dt(r["end"]) if s and fmt.startswith("Cost Explorer"): self.ce_days.add(s) if s: self.start = s if not self.start or s < self.start else self.start if e: self.end = e if not self.end or e > self.end else self.end self.durations[round((e - s).total_seconds() / 3600)] += 1 elif not self.end or s > self.end: self.end = s reg, ut = split_ut(r["ut"]) region = r["region"] or reg or "us-east-1" r["region"] = region self.regions[region] += cost self.usage_cost += cost if r["tags"]: self.tag_seen = True elif cost > 0: self.untagged[r["product"] or "Unknown"] += cost key = (r["product"], ut, r["op"], r["rid"], region, lt, r["term"]) it = self.items.get(key) if it is None: it = self.items[key] = Item(r, ut) it.cost += cost it.od_cost += r["od_cost"] if r["od_cost"] is not None else cost it.amount += r["amount"] or 0.0 it.n += 1 if s and (not it.first or s < it.first): it.first = s end = e or s if end and (not it.last or end > it.last): it.last = end if not it.tags and r["tags"]: it.tags = r["tags"] # EC2 compute series for the Savings Plan check (Linux, shared tenancy) if ut.startswith("BoxUsage") and r["product"] in ("AmazonEC2", "Unknown"): itype = r["itype"] or (ut.split(":", 1)[1] if ":" in ut else "") od = r["od_cost"] if r["od_cost"] is not None else cost if lt != "Usage": self.compute_covered += od elif r["term"] in ("OnDemand", "") and (r["op"] in ("RunInstances", "") ): env = next((str(v).lower() for k, v in r["tags"].items() if k.lower() in ENV_KEYS), "") self.compute[(s, itype, env in NONPROD, region)] += od elif r["term"] in ("OnDemand", ""): self.compute_other_os += od def finish(self): self.hours = max(1.0, (self.end - self.start).total_seconds() / 3600) if self.start and self.end else 744.0 if self.durations: mode = self.durations.most_common(1)[0][0] else: mode = 24 self.granularity = "hourly" if mode <= 1 else ("daily" if mode <= 24 else "monthly") if any(f.startswith("Cost Explorer") for f in self.formats): # Cost Explorer rows carry only a date: each row covers one day (or one month). Tell which from the distinct dates # on every row: any two less than 28 days apart means a daily download (a single date is read as one month). days = sorted(self.ce_days) step = 24 if any((y - x).days < 28 for x, y in zip(days, days[1:])) else 730 self.granularity = "daily" if step == 24 else "monthly" self.end = (self.end or self.start) + dt.timedelta(hours=step) self.hours = max(1.0, (self.end - self.start).total_seconds() / 3600) for it in self.items.values(): if it.last: it.last = it.last + dt.timedelta(hours=step) self.year = 8760.0 / self.hours first_month_days = ((self.start.replace(day=28) + dt.timedelta(days=4)).replace(day=1) - self.start.replace(day=1)).days if self.start else 31 self.month_hours = first_month_days * 24.0 if self.hours <= first_month_days * 24 + 1 else 730.0 self.total = sum(self.by_lt.values()) self.credits = -sum(v for k, v in self.by_lt.items() if k in ("Credit", "Refund")) self.tax = self.by_lt.get("Tax", 0.0) self.spend = self.total + self.credits - self.tax # what the usage cost before credits and tax disc = -sum(v for k, v in self.by_lt.items() if k in DISCOUNT_LT) self.discount_ratio = min(0.6, max(0.0, disc / self.usage_cost)) if self.usage_cost > 0 else 0.0 def find(self, pred): return [it for it in self.items.values() if pred(it)] # ---------------------------------------------------------------- rates class Rates: def __init__(self, path): with open(path) as f: self.d = json.load(f) self.used = {} self.missing = set() self.unpriced = defaultdict(lambda: [0, 0.0, set()]) # (what, region) -> [count, cost, instance types] EMPTY = {"rates": {}, "ec2": {}, "rds": {}, "tiers": {}} def reg(self, region): """A region's prices. A region not in rates.json is recorded as missing and gets no prices, never another region's.""" r = self.d["regions"].get(region) if r is None: self.missing.add(region) return self.EMPTY return r def has(self, region): return self.reg(region) is not self.EMPTY def rate(self, region, key): r = self.reg(region) v = r["rates"].get(key) if v is None: return None self.used[(region, key)] = v return v["usd"] def ec2(self, region, itype): return self.reg(region)["ec2"].get(itype) def note_ec2(self, region, itype, what="On-Demand"): e = self.ec2(region, itype) if e: idx = {"On-Demand": 0, "SP1": 1, "SP3": 2}[what] self.used[(region, f"ec2:{itype}:{what}")] = {"usd": e[idx], "unit": "hour", "code": e[idx + 3] if len(e) > idx + 3 else "", "desc": f"{itype} Linux " + {"On-Demand": "On-Demand", "SP1": "Compute Savings Plan, 1 year, No Upfront", "SP3": "Compute Savings Plan, 3 years, No Upfront"}[what], "src": (self.reg(region)["ec2_src"] if what == "On-Demand" else f"csp-{what[2]}y-{region}")} # ---------------------------------------------------------------- findings class Finding: def __init__(self, key, title, basis, low, high, summary, action, assumption, cols, rows, verify, effort, note="", now=None): self.key, self.title, self.basis, self.low, self.high = key, title, basis, max(0.0, low), max(0.0, high) self.summary, self.action, self.assumption, self.cols, self.rows = summary, action, assumption, cols, rows self.verify, self.effort, self.note, self.now = verify, effort, note, now def money(x, cents=False): if x is None: return "n/a" if cents or abs(x) < 10: return f"${x:,.2f}" return f"${x:,.0f}" def price(x): """A unit price as AWS lists it: at least 2 decimals, up to 7, no trailing zeros.""" if x is None: return "n/a" t = f"{x:.7f}".rstrip("0") if len(t.split(".")[1]) < 2: t = f"{x:.2f}" return "$" + t def yr(x): step = 100 if x >= 10000 else (10 if x >= 1000 else 1) return f"${round(x / step) * step:,.0f}" def qty(x, unit): u = unit or "" if x >= 100: return f"{x:,.0f} {u}".strip() return f"{x:,.2f} {u}".strip() def nice_ut(ut): return ut def ev_rows(items, b, extra=None, limit=8, show_op=False): rows = [] items = sorted(items, key=lambda i: -i.cost) for it in items[:limit]: ut = f"{it.ut_raw} ({it.op})" if show_op and it.op else it.ut_raw row = [it.name(), ut, it.az or it.region, qty(it.amount, it.unit) if it.amount else "", money(it.cost, cents=it.cost < 100)] if extra: row.append(extra(it)) rows.append(row) if len(items) > limit: rest = items[limit:] row = [f"and {len(rest)} more line item{'s' if len(rest) != 1 else ''}", "", "", "", money(sum(i.cost for i in rest))] if extra: row.append("") rows.append(row) return rows def period_words(b): if not b.start: return "the bill" days = round(b.hours / 24) return f"these {days} days" if days < 60 else "this period" def check_extended_support(b, R): out = [] its = b.find(lambda i: "extendedsupport" in i.ut.lower() and i.cost > 0) groups = defaultdict(list) for it in its: if "AmazonEKS" in it.ut or it.product == "AmazonEKS": kind = "eks" elif it.product == "AmazonES" or "OpenSearch" in it.ut or "EnhancedOS" in it.ut: kind = "os" elif it.product == "AmazonElastiCache" or "NodeUsage:cache." in it.ut: kind = "ec" else: kind = "rds" groups[kind].append(it) for kind, lst in groups.items(): cost = sum(i.cost for i in lst) yearly = cost * b.year low, high = 0.75 * yearly, yearly nres = len({i.rid for i in lst}) if kind == "rds": engines, steps = {}, [] for i in lst: m = re.match(r"ExtendedSupport:(Yr[0-9-]+(?:Yr\d)?):(?:ASv2:)?([A-Za-z]+)([\d.]+)", i.ut) if not m: continue band, eng, ver = m.group(1), m.group(2), m.group(3) engines[(eng, ver)] = engines.get((eng, ver), 0) + i.cost y3 = YEAR3.get(eng + ver) if band.startswith("Yr1") and y3 and b.end: d3 = dt.datetime.strptime(y3, "%Y-%m-%d") frac = (b.end + dt.timedelta(days=365) - d3).days / 365.0 if 0 < frac <= 1: r1, r3 = R.rate(i.region, "rds_es:Yr1-Yr2:" + eng + ver), R.rate(i.region, "rds_es:Yr3:" + eng + ver) if r1 and r3: high += i.cost * b.year * frac * (r3 / r1 - 1) steps.append(f"{eng} {ver} moves to the Year 3 price ({price(r3)} per vCPU-hour) on {d3:%-d %B %Y}") R.rate(i.region, "rds_es:" + i.ut.split(":", 1)[1]) names = ", ".join(f"{e} {v}" for (e, v) in sorted(engines)) moves = [f"{e} {v} to {ES_TARGET.get(e, 'a supported major version')}" for (e, v) in sorted(engines)] title = f"Upgrade {nres} RDS database{'s' if nres != 1 else ''} that AWS bills for Extended Support" summary = (f"The bill shows RDS Extended Support charges on {nres} database{'s' if nres != 1 else ''} ({names}): " f"{money(cost)} in {period_words(b)}, on top of the instances themselves. AWS enrolls databases in Extended Support " f"automatically once a major version leaves standard support, and charges per vCPU-hour, on the primary and on any Multi-AZ standby.") action = (f"Upgrade {' and '.join(moves)}. An RDS blue/green deployment lets you test the new version on a copy and switch over in a short window. " f"The charge stops when the last instance on the old version is gone.") assumption = ("Low: the upgrade lands three months from now, so nine of the next twelve months of charges are avoided. " "High: it lands now, so all twelve are avoided" + (", including the Year 3 price step: " + "; ".join(sorted(set(steps))) if steps else "") + ".") verify = "Athena on the CUR: SELECT line_item_resource_id, SUM(line_item_unblended_cost) FROM cur WHERE line_item_usage_type LIKE '%ExtendedSupport%' GROUP BY 1. Or Cost Explorer filtered to Service = RDS and the ExtendedSupport usage types." effort = "A sprint per database (test, then switch)" key = "es-rds" elif kind == "eks": ncl = nres r_ext = R.rate(lst[0].region, "eks_extended_hour") title = f"Upgrade {ncl} EKS cluster{'s' if ncl != 1 else ''} out of Kubernetes extended support" summary = (f"{ncl} cluster{'s are' if ncl != 1 else ' is'} on a Kubernetes version past standard support: the bill has " f"{qty(sum(i.amount for i in lst), 'cluster-hours')} of the extendedSupport usage type, " f"{price(r_ext) if r_ext else '$0.50'} an hour per cluster on top of the {price(R.rate(lst[0].region, 'eks_cluster_hour') or 0.10)} standard rate: {money(cost)} in {period_words(b)}.") action = ("Upgrade each cluster to Kubernetes 1.35 or later: 1.34 is still in standard support but leaves it on 2 December 2026. " "Upgrades go one minor version at a time; check for removed APIs before each step. Each version gets 14 months of standard " "support (1.35 until 27 March 2027, 1.37 until 1 December 2027), so keeping the charge off for a full year means reaching 1.37, " "or upgrading again before 27 March 2027.") assumption = "Low: the upgrades land three months from now, so nine of the next twelve months of charges are avoided. High: they land now." verify = "Cost Explorer: Service = EKS, Usage type contains \"extendedSupport\". Or: aws eks describe-cluster --name NAME --query cluster.version" effort = "A day or two per cluster" key = "es-eks" elif kind == "ec": nodes = {(i.rid, i.region) for i in lst} node_its = b.find(lambda i: i.product == "AmazonElastiCache" and i.ut.startswith("NodeUsage")) no_ids = "" in {i.rid for i in lst} # Cost Explorer: no resource IDs, so the nodes can't be told apart od_nodes = 0.0 if no_ids else sum(i.od_cost for i in node_its if (i.rid, i.region) in nodes and i.term in ("OnDemand", "")) valkey = VALKEY_CUT * od_nodes * b.year y12 = sum(i.cost for i in lst if "Yr3" not in i.ut) step = "" if y12 and b.start and b.start < EC_V6_START and b.end: # before 1 Feb 2027 only Redis OSS 4 and 5 are billed frac = (b.end + dt.timedelta(days=365) - EC_V45_YEAR3).days / 365.0 if 0 < frac <= 1: high += y12 * b.year * frac # 160% of the node price instead of 80%: the charge doubles step = f", including the Year 3 step for Redis OSS 4 and 5 (160% of the node price from {EC_V45_YEAR3:%-d %B %Y})" high += valkey others = [] if no_ids else [i for i in node_its if (i.rid, i.region) not in nodes and "redis" in (i.desc or "").lower()] od_others = sum(i.od_cost for i in others) n = f"{nres} cache node{'s' if nres != 1 else ''}" title = f"Upgrade {n} that AWS bills for ElastiCache Extended Support" summary = (f"The bill shows ElastiCache Extended Support charges on {n}: {money(cost)} in {period_words(b)}, on top of the nodes " "themselves. AWS enrolls Redis OSS caches in Extended Support automatically once their major version leaves standard support " "(versions 4 and 5 on 1 February 2026, version 6 on 1 February 2027) and charges 80% of the node's On-Demand price in Years 1 " "and 2 and 160% in Year 3; reserved nodes don't reduce it.") if b.start and b.start >= EC_V6_START: summary += " Since 1 February 2027 that includes caches on Redis OSS 6." elif others: summary += (f" The bill has {len({(i.rid, i.region) for i in others})} more Redis OSS node{'s' if len(others) != 1 else ''} not billed for it yet " f"({money(od_others)} On-Demand in {period_words(b)}). Any on Redis OSS 6 start paying the same 80% premium on 1 February 2027: " f"up to {yr(0.8 * od_others * b.year)} a year, not counted here, because the bill can't show the version.") else: summary += " Caches on Redis OSS 6 start paying it on 1 February 2027 (standard support ends 31 January 2027)." action = ("Upgrade each cache to ElastiCache for Valkey, which AWS prices 20% below Redis OSS for nodes and upgrades in place with zero downtime, " "or to Redis OSS 7, which ends the surcharge at the Redis OSS price. Check client libraries and the commands the application uses first. " "The charge stops when no node runs the old version.") assumption = ("Low: the upgrade lands three months from now, so nine of the next twelve months of Extended Support are avoided, whichever engine " "you move to. High: it lands now, so all twelve are avoided" + step + (f", and the nodes move to Valkey, which saves 20% of their On-Demand price ({yr(valkey)} a year; reserved nodes aren't counted in that part)" if valkey else (", without the Valkey saving: this export has no resource IDs, so the nodes on the old version can't be told apart" if no_ids else "")) + ".") verify = ("Cost Explorer: Service = ElastiCache, Usage type contains \"ExtendedSupport\". Versions, in each region: aws elasticache " "describe-cache-clusters --query \"CacheClusters[].[CacheClusterId,Engine,EngineVersion]\" --output table") effort = "An hour or two per cache (in-place upgrade, then a client check)" key = "es-cache" else: doms = defaultdict(list) for i in lst: doms[(i.rid, i.region)].append(i) inst = defaultdict(float) # each domain's On-Demand instance cost on the bill: the Extended Support charge since 7 Nov 2026 for i in b.find(lambda i: i.product == "AmazonES" and i.ut.startswith("ESInstance")): inst[(i.rid, i.region)] += i.od_cost yearly = old_cost = old_yearly = new_yearly = 0.0 floor, kept = False, 0 for (rid, reg), dl in doms.items(): dcost = sum(i.cost for i in dl) before = [i for i in dl if "EnhancedOS" not in i.ut and i.first and i.first < OS_DOUBLED] # Billed per normalized instance-hour after 7 Nov too, with no EnhancedOS line: Elasticsearch 5.6, which keeps that rate. still_nih = (bool(before) and not any("EnhancedOS" in i.ut for i in dl) and any(i.last and i.last > OS_DOUBLED + dt.timedelta(days=1) for i in before)) if not before or still_nih: yearly += dcost * b.year kept += still_nih continue c = sum(i.cost for i in before) old_cost += c old_yearly += dcost * b.year if inst.get((rid, reg)): y = inst[(rid, reg)] / b.hours * 8760 else: # the bill doesn't tie this domain's instances to its Extended Support line y = (dcost - c) * b.year + c * b.year * OS_MIN_RATIO floor = True new_yearly += y yearly += y low, high = 0.75 * yearly, yearly title = f"Upgrade {nres} OpenSearch domain{'s' if nres != 1 else ''} out of Extended Support" summary = f"OpenSearch Service Extended Support charges: {money(cost)} in {period_words(b)} on {nres} domain{'s' if nres != 1 else ''}." if old_cost: summary += (f" {'All' if old_cost >= cost - 0.005 else money(old_cost)} of it was billed before 7 November 2026, at the old flat rate per " "normalized instance-hour. Since 7 November " "2026 AWS charges Elasticsearch 1.5 to 7.8 (except 5.6), OpenSearch 1.0 to 1.2 and OpenSearch 2.3 to 2.9 an Extended Support fee " "equal to the instance price itself, which doubles what the domain's instances cost. So the yearly figure is at the new rate: " f"{yr(new_yearly)} a year for {'these domains' if len(doms) - kept > 1 else 'this domain'}, " + ("from the On-Demand instance cost on this bill" if not floor else "from the On-Demand instance cost on this bill, and at least 4.3 times the old charge where the bill doesn't tie a domain's " "instances to its Extended Support line (the smallest step in AWS's price list)") + f", about {new_yearly / old_yearly:.0f} times the {yr(old_yearly)} the charge on this bill would project.") if kept: summary += (f" {kept} domain{'s are' if kept != 1 else ' is'} still billed at the flat rate after 7 November, which is Elasticsearch 5.6 " f"(that rate runs to 7 November 2028), and {'stay' if kept != 1 else 'stays'} at the bill's rate.") action = ("Upgrade each domain to OpenSearch 2.19 (standard support to 7 November 2027) or 3.1 or later (no end date announced). " "Domains upgrade in place one major version at a time, so take a snapshot first; indices created on Elasticsearch 6.x must be " "reindexed before a domain can move to OpenSearch 2.x. The charge stops when the domain runs a version in standard support.") assumption = "Low: the upgrade lands three months from now, so nine of the next twelve months of charges are avoided. High: it lands now." if old_cost: assumption += (" Both are at the rate in force since 7 November 2026, not the lower rate on the earlier part of this bill. A domain on " "Elasticsearch 5.6 keeps the old rate until 7 November 2028; the bill can't show the version, so check it first.") verify = ("Cost Explorer: Service = OpenSearch Service, Usage type contains \"ExtendedSupport\" (OpenSearchExtendedSupport before 7 November " "2026, EnhancedOSExtendedSupport since). Version: aws opensearch describe-domain --domain-name NAME --query DomainStatus.EngineVersion") effort = "A day per domain" key = "es-os" if kind == "rds": cols = ["Resource", "Usage type", "Where", "Usage", "Cost", "vCPUs billed each hour"] rows = ev_rows(lst, b, extra=lambda i: f"{i.amount / (i.hours() or b.hours):,.0f}") else: cols, rows = ["Resource", "Usage type", "Where", "Usage", "Cost"], ev_rows(lst, b) out.append(Finding(key, title, "bill", low, high, summary, action, assumption, cols, rows, verify, effort, now=yearly)) return out def size_of(t): return t.split(".", 1)[1] if "." in t else "" def check_previous_generation(b, R): # An instance the non-production check switches off out of hours is counted there only, so no dollar counts twice. skip = {id(i) for i in nonprod_items(b)} its = b.find(lambda i: i.ut.startswith("BoxUsage:") and i.ltype == "Usage" and i.term in ("OnDemand", "") and (i.itype or i.ut.split(":", 1)[1]).split(".")[0] in PREV_GEN and i.op in ("RunInstances", "") and id(i) not in skip) if not its: return [] by_type = defaultdict(list) for it in its: by_type[(it.region, it.itype or it.ut.split(":", 1)[1])].append(it) low = high = cost_all = 0.0 rows = [] for (region, t), lst in sorted(by_type.items(), key=lambda kv: -sum(i.cost for i in kv[1])): fam, size = t.split(".")[0], size_of(t) cand = TARGETS.get(fam[0]) hours = sum(i.amount for i in lst) cost = sum(i.cost for i in lst) cost_all += cost old = (lst[0].rate or (R.ec2(region, t) or [None])[0] or (cost / hours if hours else 0)) if not hours and old: hours = cost / old # Cost Explorer exports carry cost only if not cand or not hours: continue def best(fams): opts = [(R.ec2(region, f"{f}.{size}")[0], f"{f}.{size}") for f in fams if R.ec2(region, f"{f}.{size}")] return min(opts) if opts else None x, a = best(cand[0]), best(cand[1]) if not x: continue R.note_ec2(region, x[1]) if a: R.note_ec2(region, a[1]) if R.ec2(region, t): R.note_ec2(region, t) s_x = max(0.0, (old - x[0])) * hours * b.year s_a = max(0.0, (old - a[0])) * hours * b.year if a else s_x low += s_x high += max(s_x, s_a) ninst = len({i.rid for i in lst}) or 1 rows.append([t, str(ninst), qty(hours, "hours"), price(old) + "/h", f"{x[1]} {price(x[0])}/h ({(1 - x[0] / old) * 100:.0f}% less)", (f"{a[1]} {price(a[0])}/h ({(1 - a[0] / old) * 100:.0f}% less)" if a else "none"), f"{yr(s_x)} to {yr(max(s_x, s_a))}"]) if high <= 0: return [] n = len({i.rid for i in its}) fams = sorted({t.split(".")[0] for (_, t) in by_type}) summary = (f"{n} instance{'s' if n != 1 else ''} run on {', '.join(fams)}: families AWS lists as previous generation. " f"The same size in a current family costs less per hour. These cost {money(cost_all)} in {period_words(b)} at On-Demand rates.") action = ("Move each to the same size in a current family. The x86 option (Intel or AMD) runs the same images unchanged; " "Graviton (arm64) is cheaper still but needs arm64 builds of your software. A stop, change of instance type and start is a few minutes per instance; " "these old families run on the Xen hypervisor and current ones on Nitro, so check that older images have the ENA and NVMe drivers " "(current Amazon Linux and Ubuntu images do).") letters = sorted({f[0] for f in fams if f[0] in TARGETS}) base = "m" if "m" in letters else (letters[0] if letters else "m") others = [x for x in letters if x != base] assumption = (f"Low: every instance moves to the cheapest same-size type among {'/'.join(TARGETS[base][0])}" + (f" (and the {' and '.join(others)} equivalents)" if others else "") + ". High: to the cheaper of that or the Graviton type.") verify = (f"Cost Explorer: Service = EC2-Instances, Instance type family = {', '.join(fams)}. Or: aws ec2 describe-instances --filters " f"Name=instance-type,Values='{','.join(f + '.*' for f in fams)}'") return [Finding("prevgen", f"Move {n} instance{'s' if n != 1 else ''} off previous-generation families", "bill", low, high, summary, action, assumption, ["Type", "Instances", "Hours", "Now", "Current x86", "Graviton", "Saving a year"], rows, verify, "An afternoon (stop, change type, start)", now=cost_all * b.year)] def check_savings_plan(b, R): if not b.compute: return [] totals = defaultdict(float) mix = defaultdict(float) for (k, t, nonprod, reg), od in b.compute.items(): if t.split(".")[0] in PREV_GEN or nonprod or not R.has(reg): continue # a region without loaded prices is left out (and flagged), not priced as another region totals[k] += od mix[(t, reg)] += od if not totals: return [] many = len({reg for (_, reg) in mix}) > 1 keys = sorted(totals) if b.granularity == "hourly": series = sorted(totals.values()) if len(series) < b.hours * 0.9: # hours with no usage at all count as zero series = [0.0] * int(b.hours - len(series)) + series floor_lo, floor_hi = series[0], series[max(0, int(len(series) * 0.10) - 1)] quiet = series[0] how = "the quietest hour of the month (low) and the 10th-percentile hour (high)" elif b.granularity == "daily": per_hour = sorted(v / 24.0 for v in totals.values()) if len(per_hour) < round(b.hours / 24) - 1: per_hour = [0.0] + per_hour floor_lo, floor_hi = 0.7 * per_hour[0], 0.9 * per_hour[0] quiet = per_hour[0] how = ("70% (low) and 90% (high) of the quietest day's average hour. The bill is daily, so the quietest hour within a day isn't visible; " "the margin allows for overnight dips") else: avg = sum(totals.values()) / b.hours floor_lo, floor_hi = 0.5 * avg, 0.7 * avg quiet = avg how = "50% (low) and 70% (high) of the average hour; a monthly bill can't show daily or hourly dips" tot = sum(mix.values()) d1 = d3 = 0.0 rows = [] known = 0.0 for (t, reg), od in sorted(mix.items(), key=lambda kv: -kv[1]): e = R.ec2(reg, t) if not e or not e[1] or not e[2]: continue known += od disc1, disc3 = 1 - e[1] / e[0], 1 - e[2] / e[0] d1 += od * disc1 d3 += od * disc3 R.note_ec2(reg, t) R.note_ec2(reg, t, "SP1") R.note_ec2(reg, t, "SP3") rows.append([f"{t} ({reg})" if many else t, money(od), f"{od / tot * 100:.0f}%", price(e[0]) + "/h", price(e[1]) + "/h", f"{disc1 * 100:.0f}%", f"{disc3 * 100:.0f}%"]) if not known: return [] d1, d3 = d1 / known, d3 / known low, high = floor_lo * d1 * 8760, floor_hi * d3 * 8760 commit = floor_lo * (1 - d1) cov = b.compute_covered / (b.compute_covered + sum(b.compute.values())) if (b.compute_covered + sum(b.compute.values())) else 0 covtxt = ("None of it is covered by a Savings Plan or reservation today." if cov < 0.01 else f"About {cov * 100:.0f}% of EC2 instance usage is already covered by Savings Plans or reservations; this is the uncovered part.") summary = (f"Even on its quietest {'day' if b.granularity == 'daily' else ('hour' if b.granularity == 'hourly' else 'month')}, the account ran {money(quiet, True)} an hour of current-generation " f"Linux EC2 at On-Demand prices. {covtxt} A Compute Savings Plan prices that steady floor " f"{d1 * 100:.0f}% lower on a 1-year term and {d3 * 100:.0f}% lower on a 3-year term, for this mix of instance types.") action = (f"Buy a Compute Savings Plan of about {money(commit, True)} an hour (1 year, No Upfront). It applies automatically to EC2 in any family, size " f"and region, and to Fargate and Lambda, so later changes such as the instance moves in this memo stay covered. Size it from AWS's own recommendation " f"page too, and buy in two steps if you prefer.") assumption = (f"The commitment covers only the floor: {how}. Low: 1-year term. High: 3-year term. Previous-generation and non-production instances are left " f"out of the floor because other findings change them.") verify = "Billing and Cost Management > Savings Plans > Recommendations (Compute, 1 year, No Upfront, 30-day lookback) gives AWS's own figure to compare." return [Finding("sp", "Cover steady compute with a Compute Savings Plan", "bill", low, high, summary, action, assumption, ["Instance type", "On-Demand cost", "Share", "On-Demand", "1-yr plan rate", "1-yr discount", "3-yr discount"], rows[:8], verify, "An hour to buy", now=tot * b.year)] def check_gp3(b, R): vols = b.find(lambda i: i.ut.endswith("VolumeUsage.gp2") and i.ltype == "Usage") if not vols: return [] low = high = cost = 0.0 rows = [] det = [] for v in vols: if b.end and v.last and (b.end - v.last).total_seconds() > 36 * 3600: continue # deleted before the end of the bill h = v.hours() or b.hours g2, g3 = R.rate(v.region, "ebs_gp2"), R.rate(v.region, "ebs_gp3") iops_r, tput_r = R.rate(v.region, "ebs_gp3_iops"), R.rate(v.region, "ebs_gp3_gibps") gbmo = v.amount or (v.cost / g2 if g2 else 0) # Cost Explorer exports carry cost only size = gbmo * b.month_hours / h if not (g2 and g3 and size): continue s_hi = size * (g2 - g3) * 12 if v.rid: iops = min(16000, max(100, 3 * size)) tput = 128 if size <= 170 else 250 extra = max(0, iops - 3000) * iops_r + max(0, tput - 125) * tput_r / 1024 s_lo = max(0.0, size * (g2 - g3) - extra) * 12 else: # all volumes in one row: sizes unknown, so the low end takes half extra, s_lo = 0.0, s_hi / 2 high += s_hi low += s_lo cost += v.cost det.append((s_hi, v, size, extra, s_lo)) if high <= 0: return [] det.sort(key=lambda x: -x[0]) for s_hi, v, size, extra, s_lo in det[:8]: rows.append([v.name(), v.az or v.region, f"{size:,.0f} GiB", money(size * R.rate(v.region, 'ebs_gp2')) + "/mo", money(size * R.rate(v.region, 'ebs_gp3')) + "/mo", (money(extra) + "/mo" if extra >= 1 else "none"), f"{yr(s_lo)} to {yr(s_hi)}"]) if len(det) > 8: rows.append([f"and {len(det) - 8} more volumes", "", f"{sum(d[2] for d in det[8:]):,.0f} GiB", "", "", "", f"{yr(sum(d[4] for d in det[8:]))} to {yr(sum(d[0] for d in det[8:]))}"]) tb = sum(d[2] for d in det) / 1024 reg = det[0][1].region summary = (f"{len(det)} volumes ({tb:,.1f} TiB) are still gp2. gp3 costs {price(R.rate(reg, 'ebs_gp3'))} per GB-month against gp2's " f"{price(R.rate(reg, 'ebs_gp2'))} in {reg}, and includes 3,000 IOPS and 125 MiB/s whatever the size. They cost {money(cost)} in {period_words(b)}.") action = ("Change each volume's type to gp3 (EC2 > Volumes > Modify, or aws ec2 modify-volume --volume-type gp3). It happens online with no detach " "or downtime. For volumes over 1 TiB, set the IOPS to what the workload actually uses (CloudWatch VolumeReadOps/VolumeWriteOps), not gp2's " "3 IOPS per GiB.") assumption = ("High: gp3's included 3,000 IOPS and 125 MiB/s are enough for every volume. Low: every volume is given gp2's full baseline " "(3 IOPS per GiB, and 250 MiB/s above 170 GiB) at gp3's provisioned IOPS and throughput prices.") verify = "aws ec2 describe-volumes --filters Name=volume-type,Values=gp2 --query 'Volumes[].[VolumeId,Size]'" return [Finding("gp3", f"Switch {len(det)} gp2 volumes to gp3", "bill", low, high, summary, action, assumption, ["Volume", "Zone", "Size", "gp2", "gp3", "Extra to match gp2 (worst case)", "Saving a year"], rows, verify, "An afternoon (online change)", now=cost * b.year)] def check_ipv4(b, R): idle = b.find(lambda i: i.ut.endswith("PublicIPv4:IdleAddress") and i.cost > 0) out = [] if idle: cost = sum(i.cost for i in idle) r_ip = R.rate(idle[0].region, "ipv4_idle") or 0.005 for i in idle: if not i.amount: i.amount = i.cost / r_ip # Cost Explorer exports carry cost only n = sum(i.amount for i in idle) / b.hours summary = (f"The bill charges for idle public IPv4 addresses: {qty(sum(i.amount for i in idle), 'address-hours')}, about {n:.0f} addresses " f"held all period without being attached to anything running, at $0.005 an hour each: {money(cost, True)} in {period_words(b)}.") out.append(Finding("ipv4", f"Release {n:.0f} unused Elastic IP addresses", "bill", 0.75 * cost * b.year, cost * b.year, summary, "Release the Elastic IPs nobody uses (EC2 > Elastic IPs, or aws ec2 release-address). Keep any that partners have allowlisted.", "Low: a quarter are kept on purpose (for example, addresses partners allowlist). High: all are released.", ["Resource", "Usage type", "Where", "Usage", "Cost"], ev_rows(idle, b), "aws ec2 describe-addresses --query 'Addresses[?AssociationId==null].[PublicIp,AllocationId]'", "Minutes", now=cost * b.year)) return out def idle_nats(b): """NAT gateways billed most hours that processed under 1 GB a day: resource ID -> their line items.""" nats = defaultdict(lambda: {"hours": 0.0, "gb": 0.0, "items": []}) for it in b.find(lambda i: ("NatGateway-Hours" in i.ut or "NatGateway-Bytes" in i.ut) and i.rid): d = nats[it.rid] d["items"].append(it) if "Hours" in it.ut: d["hours"] += it.amount else: d["gb"] += it.amount return {rid: d["items"] for rid, d in nats.items() if d["hours"] >= 0.5 * b.hours and d["gb"] < max(1.0, b.hours / 24)} def check_idle_lb(b, R): lbs = defaultdict(lambda: {"hours": 0.0, "work": 0.0, "cost": 0.0, "items": [], "kind": ""}) for it in b.find(lambda i: i.product == "AWSELB" and i.rid): d = lbs[it.rid] d["items"].append(it) d["cost"] += it.cost if it.ut.endswith("LoadBalancerUsage"): d["hours"] += it.amount d["kind"] = "ALB" if "Application" in it.op else ("NLB" if "Network" in it.op else ("GWLB" if "Gateway" in it.op else "Classic")) elif it.ut.endswith("LCUUsage") or it.ut.endswith("DataProcessing-Bytes"): d["work"] += it.amount idle_items, cost, names = [], 0.0, [] for rid, d in lbs.items(): if d["hours"] >= 0.5 * b.hours and d["work"] < 0.01 * d["hours"] + 0.5: idle_items += d["items"] cost += d["cost"] names.append(f"{d['kind']} {short_rid(rid)}") for rid, items in idle_nats(b).items(): idle_items += items cost += sum(i.cost for i in items) names.append(f"NAT gateway {short_rid(rid)}") if not idle_items: return [] n = len(names) summary = (f"{n} load balancer{'s' if n != 1 else ''} or NAT gateway{'s' if n != 1 else ''} were billed for every hour but handled almost no traffic: " f"under 0.01 capacity units an hour for load balancers, under 1 GB a day for NAT gateways. Together {money(cost, True)} in {period_words(b)}.") return [Finding("idle", f"Delete {n} idle load balancer{'s' if n != 1 else ''} and NAT gateway{'s' if n != 1 else ''}", "bill", 0.75 * cost * b.year, cost * b.year, summary, "Confirm nothing points at them (DNS records, target groups with no healthy targets), then delete them.", "Low: a quarter turn out to be kept on purpose (standby or disaster recovery). High: all are deleted.", ["Resource", "Usage type", "Where", "Usage", "Cost"], ev_rows(idle_items, b, limit=10), "aws elbv2 describe-target-health, and the RequestCount / ProcessedBytes metrics for each one in CloudWatch", "Under an hour", now=cost * b.year)] def check_nat(b, R): idle = idle_nats(b) # deleted by the idle finding, so their bytes aren't counted here as well gb_items = b.find(lambda i: "NatGateway-Bytes" in i.ut and i.cost > 0 and i.rid not in idle) if not gb_items: return [] gb = sum(i.amount for i in gb_items) cost = sum(i.cost for i in gb_items) if cost * b.year < 1000: return [] by_reg = defaultdict(float) for i in gb_items: by_reg[i.region] += i.cost reg = max(by_reg, key=by_reg.get) rate = R.rate(reg, "nat_gb") or (cost / gb if gb else 0) vgb, vhr = R.rate(reg, "vpce_gb"), R.rate(reg, "vpce_hour") at = f"at {price(rate)} per GB" if len(by_reg) == 1 else f"across {len(by_reg)} regions, {price(round(cost / gb, 4))} per GB on average" summary = (f"NAT gateways processed {gb / 1024:,.1f} TB in {period_words(b)} {at}: {money(cost)}. Traffic from private subnets to S3 " f"or DynamoDB in the same region doesn't need to pass through a NAT gateway at all: a gateway endpoint carries it for free.") action = ("Add S3 and DynamoDB gateway endpoints to the private subnets' route tables (free, a few minutes in the console, no app changes). " "Container image layers pulled from ECR are stored in S3, so the S3 endpoint carries most of that traffic too. " + (f"Interface endpoints for other AWS services cost {price(vgb)} per GB plus {price(vhr)} an hour per zone, so one pays " f"off above about {3 * 730 * vhr / max(0.001, rate - vgb):,.0f} GB a month in three zones." if vgb and vhr else "Interface endpoints for other AWS services charge per GB and per hour in each zone, so they pay off only for busy services.")) assumption = ("The bill can't show where NAT traffic goes. Low: 15% of it is S3 or DynamoDB traffic in the same region. High: 40%. " "VPC Flow Logs on the NAT gateway's network interface show the real share in a day.") verify = ("VPC Flow Logs for the NAT gateway's ENI, grouped by destination; S3 and DynamoDB destinations are in the managed prefix lists " "(aws ec2 describe-managed-prefix-lists).") return [Finding("nat", "Route S3 and DynamoDB traffic around the NAT gateways", "check", 0.15 * cost * b.year, 0.40 * cost * b.year, summary, action, assumption, ["Resource", "Usage type", "Where", "Usage", "Cost"], ev_rows(gb_items, b), verify, "Under an hour", now=cost * b.year)] def check_inter_az(b, R): its = b.find(lambda i: i.ut.endswith("DataTransfer-Regional-Bytes") and i.cost > 0) if not its: return [] cost = sum(i.cost for i in its) gb = sum(i.amount for i in its) if cost * b.year < 1000: return [] R.rate(its[0].region, "dt_inter_az") summary = (f"Traffic between availability zones cost {money(cost)} in {period_words(b)} ({gb / 1024:,.1f} TB counted at $0.01 per GB in each direction). " f"It's traffic between your own resources in different zones, and the chattiest pairs can often be kept inside one zone.") action = ("Find the chattiest pairs (VPC Flow Logs with the AZ fields, or your Kubernetes cost tool) and keep them zone-local: topology-aware routing " "in Kubernetes, consumers reading from a replica in their own zone, caches and read replicas placed with their clients.") assumption = "The bill can't show which services talk to which. Low: 20% of inter-zone traffic is removed. High: 50%." verify = "Athena on the CUR: SELECT line_item_resource_id, SUM(line_item_usage_amount) FROM cur WHERE line_item_usage_type LIKE '%DataTransfer-Regional-Bytes' GROUP BY 1 ORDER BY 2 DESC." return [Finding("interaz", "Keep chatty services inside one availability zone", "check", 0.2 * cost * b.year, 0.5 * cost * b.year, summary, action, assumption, ["Resource", "Usage type", "Where", "Usage", "Cost"], ev_rows(its, b, show_op=True), verify, "A sprint", now=cost * b.year)] def check_logs(b, R): its = b.find(lambda i: i.product == "AmazonCloudWatch" and re.search(r"(^|-)DataProcessing-Bytes$", i.ut) and i.cost > 0) if not its: return [] cost = sum(i.cost for i in its) if cost * b.year < 1000: return [] groups = defaultdict(float) for i in its: groups[(i.rid, i.region)] += i.cost cuts = {} # each log group priced at its own region's rates; a region without loaded prices is left out for (_, reg) in groups: if reg not in cuts: s_, ia_ = R.rate(reg, "logs_ingest_std"), R.rate(reg, "logs_ingest_ia") cuts[reg] = 1 - ia_ / s_ if (s_ and ia_) else None top = sorted(((c, cuts[reg], reg) for (_, reg), c in groups.items() if cuts[reg] is not None), key=lambda x: -x[0]) if not top: return [] reg = top[0][2] std, ia = R.rate(reg, "logs_ingest_std"), R.rate(reg, "logs_ingest_ia") low = top[0][0] * top[0][1] * b.year high = sum(c * cut for c, cut, _ in top[:3]) * b.year share3 = sum(c for c, _, _ in top[:3]) / cost store = b.find(lambda i: i.product == "AmazonCloudWatch" and i.ut.endswith("TimedStorage-ByteHrs")) store_cost = sum(i.cost for i in store) where = "" if len(cuts) == 1 else f" in {reg}, the region of the largest log group" summary = (f"CloudWatch Logs ingestion cost {money(cost)} in {period_words(b)} at {price(std)} per GB (Standard class){where}. " f"The three largest log groups are {share3 * 100:.0f}% of it. The Essentials log class (formerly Infrequent Access) ingests at " f"{price(ia)} per GB and keeps Logs Insights queries and export to S3.") if store_cost * b.year > 500: summary += (f" Log storage is another {money(store_cost)}; log groups with no retention setting keep everything forever, and setting one is a " f"single command per group. That isn't counted here because the bill can't show retention settings.") action = ("For the big log groups that people only search when debugging, create an Essentials-class log group and point the app at it (a log group's " "class can't be changed after creation). Essentials drops Live Tail, metric filters, subscription filters, embedded metric format and the " "GetLogEvents/FilterLogEvents APIs (you read events with Logs Insights), so keep groups that feed alarms, metrics or other systems on Standard. " "Lowering the log level of the noisiest service saves more still.") assumption = "Low: only the largest log group moves to Essentials. High: the three largest move." verify = "aws logs describe-log-groups --query 'logGroups[].[logGroupName,storedBytes,retentionInDays,logGroupClass]'" return [Finding("logs", "Move the biggest log groups to the cheaper Essentials class", "check", low, high, summary, action, assumption, ["Log group", "Usage type", "Where", "Ingested", "Cost"], ev_rows(its, b), verify, "A day", now=cost * b.year)] def check_s3(b, R): buckets = defaultdict(lambda: {"gbmo": 0.0, "cost": 0.0, "get": 0.0, "put": 0.0, "items": [], "region": ""}) for it in b.find(lambda i: i.product == "AmazonS3" and i.rid): d = buckets[it.rid] d["region"] = it.region if it.ut == "TimedStorage-ByteHrs": d["gbmo"] += it.amount d["cost"] += it.cost d["items"].append(it) elif it.ut.startswith("Requests-Tier2"): d["get"] += it.amount elif it.ut.startswith("Requests-Tier1"): d["put"] += it.amount cold = [] for name, d in buckets.items(): gb = d["gbmo"] * b.month_hours / b.hours # each bucket priced at its own region's rates; a region without loaded prices is left out (and flagged) if (gb >= 1024 and d["get"] / max(gb, 1) * (b.month_hours / b.hours) < 1.0 and R.rate(d["region"], "s3_sia") and R.rate(d["region"], "s3_gir")): cold.append((name, d, gb)) if not cold: return [] low = high = cost = 0.0 rows = [] cold.sort(key=lambda c: -c[1]["cost"]) reg = cold[0][1]["region"] sia, gir = R.rate(reg, "s3_sia"), R.rate(reg, "s3_gir") for name, d, gb in cold: eff = d["cost"] / d["gbmo"] if d["gbmo"] else 0.023 lo = 0.5 * gb * max(0, eff - R.rate(d["region"], "s3_sia")) * 12 hi = 0.8 * gb * max(0, eff - R.rate(d["region"], "s3_gir")) * 12 low += lo high += hi cost += d["cost"] gets_mo = d["get"] * b.month_hours / b.hours rows.append([name, f"{gb / 1024:,.1f} TiB", f"{gets_mo:,.0f}", f"{gets_mo / gb:.2f}", money(d["cost"]), f"{yr(lo)} to {yr(hi)}"]) summary = (f"{len(cold)} bucket{'s hold' if len(cold) != 1 else ' holds'} {sum(c[2] for c in cold) / 1024:,.1f} TiB in S3 Standard but " f"{'are' if len(cold) != 1 else 'is'} read less than once a month per GB, judging by GET requests. Standard costs " f"{price(round(cold[0][1]['cost'] / cold[0][1]['gbmo'], 5) if cold[0][1]['gbmo'] else 0.023)} per GB-month " f"{'here' if len({c[1]['region'] for c in cold}) == 1 else 'in ' + reg + ', the region of the largest bucket'}; Standard-IA costs " f"{price(sia)} and Glacier Instant Retrieval {price(gir)}, both with millisecond reads.") action = ("Add a lifecycle rule that moves objects older than 30 days to Standard-IA, or older than 90 days to Glacier Instant Retrieval, or turn on " "Intelligent-Tiering. Check object sizes first: objects under 128 KB are billed as 128 KB in these classes, and each GB read back costs " f"{price(R.rate(reg, 's3_sia_retrieval') or 0.01)} (Standard-IA) or {price(R.rate(reg, 's3_gir_retrieval') or 0.03)} (Glacier Instant Retrieval).") assumption = ("The bill shows bytes and requests, not object ages. Low: half the bytes move to Standard-IA. High: 80% move to Glacier Instant " "Retrieval. S3 Storage Lens shows the real age profile.") verify = "S3 Storage Lens (free metrics) or S3 Inventory shows object ages and sizes per bucket." return [Finding("s3", f"Move {len(cold)} rarely read S3 bucket{'s' if len(cold) != 1 else ''} to cheaper storage classes", "check", low, high, summary, action, assumption, ["Bucket", "Standard storage", "GET requests a month", "GETs per GB", "Cost", "Saving a year"], rows, verify, "A day", now=cost * b.year)] def check_snapshots(b, R): snaps = b.find(lambda i: i.ut.endswith("SnapshotUsage") and i.product == "AmazonEC2" and i.cost > 0) if not snaps: return [] cost = sum(i.cost for i in snaps) vols = b.find(lambda i: "VolumeUsage" in i.ut and i.product == "AmazonEC2") vcost = sum(i.cost for i in vols) if cost * b.year < 1000: return [] snap_gb = sum(i.amount for i in snaps) * b.month_hours / b.hours vol_gb = sum(i.amount for i in vols) * b.month_hours / b.hours new = sum(1 for i in snaps if b.start and i.first and (i.first - b.start).total_seconds() >= 24 * 3600) gone = sum(1 for i in snaps if b.end and i.last and (b.end - i.last).total_seconds() > 36 * 3600) days = max(1.0, b.hours / 24) reg = snaps[0].region R.rate(reg, "ebs_snapshot") R.rate(reg, "ebs_snapshot_archive") summary = (f"EBS snapshots cost {money(cost)} in {period_words(b)}, {cost / vcost * 100:.0f}% of what the volumes themselves cost " f"({snap_gb / 1024:,.1f} TiB of snapshot storage against {vol_gb / 1024:,.1f} TiB of volumes). The bill lists {len(snaps)} snapshots, " f"{new} of them created during the period (about {new / days:.0f} a day), and " + ("none deleted." if gone == 0 else f"only {gone} deleted.")) arch, std = R.rate(reg, "ebs_snapshot_archive"), R.rate(reg, "ebs_snapshot") action = ("Put a retention period on snapshots with Amazon Data Lifecycle Manager or AWS Backup (for example 30 daily copies and 12 monthly ones), " "delete snapshots of volumes that no longer exist, and move copies kept only for compliance to the snapshot archive tier (" + (f"{price(arch)} per GB-month instead of {price(std)}, " if arch and std else "") + "with a 90-day minimum; archived snapshots are stored in full rather than incrementally, so this suits monthly or yearly copies).") assumption = ("The bill doesn't show snapshot ages. Low: a retention policy removes a quarter of snapshot storage. High: half. " "Snapshots are incremental, so deleting old ones frees less than their count suggests.") verify = "aws ec2 describe-snapshots --owner-ids self --query 'Snapshots[].[SnapshotId,VolumeId,VolumeSize,StartTime]' --output text | sort -k4" return [Finding("snap", "Expire old EBS snapshots", "check", 0.25 * cost * b.year, 0.5 * cost * b.year, summary, action, assumption, ["Snapshot", "Usage type", "Where", "Usage", "Cost"], ev_rows(snaps, b), verify, "An afternoon", now=cost * b.year)] ENGINE_OP = {"0002": "MySQL", "0014": "PostgreSQL", "0016": "Aurora MySQL", "0021": "Aurora PostgreSQL", "0018": "MariaDB"} def check_rds_reserved(b, R): its = b.find(lambda i: i.product == "AmazonRDS" and re.match(r"^(InstanceUsage|Multi-AZUsage):db\.", i.ut) and i.ltype == "Usage" and i.term in ("OnDemand", "")) rows, low, high, cost, od_sum, ri_sum, newer = [], 0.0, 0.0, 0.0, 0.0, 0.0, False for it in sorted(its, key=lambda i: -i.cost): if it.amount < 0.9 * b.hours: continue # only databases that ran the whole period eng = ENGINE_OP.get(it.op.rsplit(":", 1)[-1], "") dep = "Multi-AZ" if it.ut.startswith("Multi-AZ") else "Single-AZ" t = re.sub(r"\.(\d*)xl$", r".\1xlarge", it.itype or it.ut.split(":", 1)[1]) key = f"{t}|{eng}|{dep}" if not R.has(it.region): continue # the whole region is flagged as unpriced in the memo e = R.reg(it.region).get("rds", {}).get(key) if not e or len(e) < 6 or not e[2]: u = R.unpriced[("rds-ri", it.region)] # flagged in the memo, never skipped silently u[0], u[1] = u[0] + 1, u[1] + it.cost u[2].add(f"{t} {eng or 'other engine'}") continue od = it.rate or e[0] lo = max(0.0, od - e[2]) * it.amount * b.year hi = max(lo, (od - e[4]) * it.amount * b.year) if e[4] else lo low, high, cost = low + lo, high + hi, cost + it.cost od_sum, ri_sum = od_sum + od * it.amount, ri_sum + e[2] * it.amount m = re.match(r"db\.[a-z]+(\d)", t) newer = newer or bool(m and int(m.group(1)) >= 7) reg = it.region src = R.reg(it.region).get("rds_src", "") R.used[(reg, f"rds:{key}:od")] = {"usd": e[0], "unit": "hour", "code": e[1], "src": src, "desc": f"{t} {eng} {dep}, On-Demand"} R.used[(reg, f"rds:{key}:ri1")] = {"usd": e[2], "unit": "hour", "code": e[3], "src": src, "desc": f"{t} {eng} {dep}, reserved 1 year, No Upfront"} if e[4]: R.used[(reg, f"rds:{key}:ri3")] = {"usd": e[4], "unit": "hour", "code": e[5], "src": src, "desc": f"{t} {eng} {dep}, reserved 3 years, Partial Upfront (upfront spread over the term)"} if len(e) >= 9 and e[7]: # the price list's two parts, so each can be looked up R.used[(reg, f"rds:{key}:ri3")].update( parts=f"{price(e[6])} an hour plus {money(e[7])} upfront, spread over {3 * 8760:,} hours", code2=e[8]) rows.append([it.name(), t, f"{eng}, {dep}", qty(it.amount, "hours"), price(od) + "/h", f"{price(e[2])}/h ({(1 - e[2] / od) * 100:.0f}% less)", (f"{price(e[4])}/h ({(1 - e[4] / od) * 100:.0f}% less)" if e[4] else "not offered"), f"{yr(lo)} to {yr(hi)}"]) if not rows: return [] n = len(rows) disc = (1 - ri_sum / od_sum) * 100 if od_sum else 0 summary = (f"{n} database instance{'s' if n != 1 else ''} ran every hour of the period at On-Demand prices, {money(cost)} in {period_words(b)}, " f"with no reservation covering {'them' if n != 1 else 'it'}. A 1-year reservation with nothing paid up front prices the same " f"instances {disc:.0f}% lower; Extended Support charges, if any, are separate and not affected.") sp_note = ("AWS's Database Savings Plans (1 year, No Upfront) are an alternative for the 7th-generation instances here." if newer else "AWS's Database Savings Plans cover RDS only on 7th-generation and newer families (m7g, m7i, r7g, r7i, m8g, r8g " "and later), so for these instances reservations are the way.") action = ("Reserve the databases that run all the time, after any planned change of instance family or engine (RDS > Reserved instances > " "Purchase). For MySQL, MariaDB, PostgreSQL and Aurora a reservation is size-flexible within its instance family, and a major version " "upgrade doesn't change it. " + sp_note) assumption = ("Only databases that ran the whole period count. Low: 1-year reservations, nothing up front. High: 3-year reservations, " "partial up front, with the upfront payment spread over the three years.") verify = "Billing and Cost Management > Reservations > Recommendations (RDS, 1 year, No Upfront) gives AWS's own figure to compare." return [Finding("rds-ri", f"Reserve {n} database{'s' if n != 1 else ''} that run{'' if n != 1 else 's'} around the clock", "bill", low, high, summary, action, assumption, ["Database", "Instance", "Engine", "Hours", "On-Demand", "1-yr reserved", "3-yr reserved", "Saving a year"], rows, verify, "An hour to buy", now=cost * b.year)] def nonprod_items(b): """Instances tagged non-production that ran 90%+ of the period, if together they're worth a finding.""" its = [] for it in b.find(lambda i: i.ut.startswith("BoxUsage") and i.ltype == "Usage" and i.tags): env = next((str(v).lower() for k, v in it.tags.items() if k.lower() in ENV_KEYS), "") if env in NONPROD and it.amount >= 0.9 * b.hours: its.append(it) if sum(i.cost for i in its) * b.year < 1000: return [] return its def check_nonprod(b, R): its = nonprod_items(b) if not its: return [] cost = sum(i.cost for i in its) envs = sorted({next((str(v) for k, v in i.tags.items() if k.lower() in ENV_KEYS), "") for i in its}) summary = (f"{len(its)} instances tagged {', '.join(envs)} ran every hour of the period: {money(cost)} in {period_words(b)}. " f"Non-production machines are usually needed during working hours only.") action = ("Stop them outside working hours with AWS Instance Scheduler or a scheduled Auto Scaling action (for EKS node groups, scale to zero at night). " "Their EBS volumes keep billing while stopped, which is already left out of this figure.") assumption = ("Low: off on weeknights only (12 hours a day, Monday to Friday: 36% fewer hours). High: off nights and weekends " "(on 12 hours a day on weekdays only: 64% fewer hours).") verify = "Cost Explorer: Service = EC2-Instances, Tag env = " + ", ".join(envs) + ", Group by Instance type." return [Finding("nonprod", f"Turn off {len(its)} non-production instances out of hours", "check", 0.36 * cost * b.year, 0.64 * cost * b.year, summary, action, assumption, ["Resource", "Usage type", "Where", "Usage", "Cost"], ev_rows(its, b), verify, "A day to set up", now=cost * b.year)] CHECKS = [check_extended_support, check_savings_plan, check_rds_reserved, check_previous_generation, check_gp3, check_snapshots, check_nat, check_logs, check_s3, check_inter_az, check_nonprod, check_idle_lb, check_ipv4] def notes(b, R): """Worth a look, not counted.""" out = [] inuse = b.find(lambda i: i.ut.endswith("PublicIPv4:InUseAddress") and i.cost > 0) if inuse: c = sum(i.cost for i in inuse) n = sum(i.amount for i in inuse) / b.hours out.append(f"Public IPv4 addresses in use: about {n:.0f} addresses on running resources cost {money(c)} in {period_words(b)} " f"({yr(c * b.year)} a year). Instances that sit behind a load balancer don't need their own public address; turning off " f"auto-assign public IP on those subnets removes it. Not counted, because the bill can't show which instances need one.") # Regional transfer out to the internet only: CloudFront's edge usage types (IN-, US-, EU-...) are already CloudFront. egress = b.find(lambda i: i.ut == "DataTransfer-Out-Bytes" and i.product != "AmazonCloudFront" and i.cost > 0) if egress: c = sum(i.cost for i in egress) gb = sum(i.amount for i in egress) out.append(f"Data transfer to the internet: {gb / 1024:,.1f} TB, {money(c)} in {period_words(b)}. If much of it is static files or " f"cacheable API responses, serving it through CloudFront (transfer from AWS origins to CloudFront is free) usually costs less. " f"Not counted, because the bill doesn't show what the traffic is.") if b.tag_seen: un = sum(b.untagged.values()) if b.usage_cost > 0 and un / b.usage_cost > 0.05: top = sorted(b.untagged.items(), key=lambda kv: -kv[1])[:3] out.append(f"Spend with no cost-allocation tag: {money(un)} ({un / b.usage_cost * 100:.0f}% of usage) carries no user tag, mostly " + ", ".join(f"{esc(SERVICE_NAMES.get(k, k))} ({money(v)})" for k, v in top) + ". Untagged spend has no owner, which is how idle resources survive. A tag policy (team, service, env) and activating " "those tags for cost allocation fixes it going forward.") elif any(f.startswith("Cost and Usage") for f in b.formats) and b.tag_cols: # columns deleted: nothing to say out.append("No cost-allocation tags: the report carries no user tags at all, so no spend can be traced to a team or service. " "Activate your tags under Billing > Cost allocation tags; they appear in the report from then on.") if b.compute_other_os > 0: out.append(f"Windows or licensed-OS instances: {money(b.compute_other_os)} of On-Demand EC2 runs an OS other than Linux. " f"Savings Plans cover these too; they aren't in the Savings Plan figure above, which counts Linux only.") return out CANT_SEE = [ ("Unattached EBS volumes", "billing shows each volume's cost, not whether it's attached", "aws ec2 describe-volumes --filters Name=status,Values=available --query 'Volumes[].[VolumeId,Size,VolumeType,CreateTime]'"), ("Oversized instances and databases", "billing has no CPU or memory use", "AWS Compute Optimizer (free) lists over-provisioned instances, Auto Scaling groups, EBS volumes and Lambda functions"), ("Idle databases", "an RDS instance with no connections bills the same as a busy one", "CloudWatch metric DatabaseConnections, maximum over 14 days, for each DB instance"), ("Where NAT and inter-zone traffic goes", "billing has bytes, not destinations", "VPC Flow Logs on the relevant network interfaces"), ("Log retention and object ages", "billing has stored bytes, not settings or ages", "aws logs describe-log-groups (retentionInDays), and S3 Storage Lens"), ] # ---------------------------------------------------------------- memo CSS = """ :root{--bg:#fbfaf7;--surface:#fff;--ink:#1c2126;--muted:#5b6168;--line:#e3e0d8;--box:#f3f1ec;--accent:#0d6157;--tint:#e6f0ed;--warn:#8a5a00;--warnbg:#fbf3e2; --sans:"IBM Plex Sans",-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;--mono:"IBM Plex Mono",ui-monospace,SFMono-Regular,Menlo,Consolas,monospace} @media (prefers-color-scheme:dark){:root{--bg:#121416;--surface:#181b1e;--ink:#e9e7e2;--muted:#a3a7ab;--line:#2c3034;--box:#1b1f22;--accent:#63c7b4;--tint:#15302b;--warn:#e7b85a;--warnbg:#2a2213}} *{box-sizing:border-box} body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.6 var(--sans);-webkit-text-size-adjust:100%;overflow-wrap:break-word} main{max-width:920px;margin:0 auto;padding:28px 16px 64px} h1{font-size:1.75rem;line-height:1.2;margin:6px 0 8px;letter-spacing:-.01em} h2{font-size:1.25rem;margin:44px 0 10px;line-height:1.3} h3{font-size:1.08rem;margin:0 0 6px;line-height:1.35} p{margin:0 0 10px} a{color:var(--accent)} code,.mono{font-family:var(--mono);font-size:.86em} .eyebrow{font-family:var(--mono);font-size:.74rem;letter-spacing:.06em;text-transform:uppercase;color:var(--muted);margin:0} .meta{color:var(--muted);font-size:.93rem} .banner{background:var(--warnbg);border:1px solid var(--line);border-left:3px solid var(--warn);border-radius:6px;padding:12px 14px;margin:16px 0} .kpis{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px;margin:18px 0} .kpi{background:var(--surface);border:1px solid var(--line);border-radius:8px;padding:12px 14px} .kpi .v{font-size:1.35rem;font-weight:600;line-height:1.25} .kpi .l{color:var(--muted);font-size:.85rem} .scroll{overflow-x:auto;-webkit-overflow-scrolling:touch;margin:8px 0 12px} table{border-collapse:collapse;width:100%;font-size:.88rem} th,td{text-align:left;vertical-align:top;padding:7px 10px 7px 0;border-bottom:1px solid var(--line)} th{font-weight:600;color:var(--muted);font-size:.8rem;white-space:nowrap} td.n,th.n{text-align:right;white-space:nowrap;padding-left:8px} td.id{font-family:var(--mono);font-size:.8rem;word-break:break-all;min-width:9em} table.ev td{white-space:nowrap}table.ev td.id{white-space:normal;min-width:11em} .f{background:var(--surface);border:1px solid var(--line);border-radius:8px;padding:18px 18px 8px;margin:18px 0} .f-head{display:flex;justify-content:space-between;gap:12px;align-items:flex-start;flex-wrap:wrap} .amt{font-size:1.15rem;font-weight:600;white-space:nowrap} .tag{display:inline-block;font-family:var(--mono);font-size:.7rem;letter-spacing:.04em;text-transform:uppercase;border-radius:4px;padding:2px 6px;margin-right:6px} .tag.bill{background:var(--tint);color:var(--accent)} .tag.check{background:var(--warnbg);color:var(--warn)} .rank{font-family:var(--mono);color:var(--muted);margin-right:6px} .lbl{font-weight:600} .small{font-size:.88rem;color:var(--muted)} ul,ol{padding-left:1.25em;margin:0 0 12px} li{margin:0 0 6px} details{margin:8px 0 12px}summary{cursor:pointer;color:var(--accent);font-weight:500} td a{text-decoration:none}td a:hover{text-decoration:underline} .cta{background:var(--tint);border-radius:10px;padding:20px 20px 12px;margin-top:20px} footer{margin-top:44px;padding-top:14px;border-top:1px solid var(--line);color:var(--muted);font-size:.88rem} @media (max-width:640px){.kpis{grid-template-columns:1fr}h1{font-size:1.45rem}.f{padding:14px 14px 6px}} @media print{body{background:#fff}.f{break-inside:avoid}} """ PLAUSIBLE = """ """ def esc(s): return html.escape(str(s), quote=True) def table(cols, rows, numeric=(), idcol=True, raw=(), tclass=""): h = "".join(f'{esc(c)}' if i in numeric else f"{esc(c)}" for i, c in enumerate(cols)) body = [] for r in rows: cells = [] for i, c in enumerate(r): cls = ' class="n"' if i in numeric else (' class="id"' if i == 0 and idcol else "") cells.append(f"{c if i in raw else esc(c)}") body.append("" + "".join(cells) + "") return f'
{h}{"".join(body)}
' LABELS = { "ebs_gp2": "EBS gp2 storage", "ebs_gp3": "EBS gp3 storage", "ebs_gp3_iops": "EBS gp3 IOPS above the included 3,000", "ebs_gp3_gibps": "EBS gp3 throughput above the included 125 MiB/s", "ebs_snapshot": "EBS snapshot storage", "ebs_snapshot_archive": "EBS snapshot archive storage", "nat_gb": "NAT gateway data processed", "nat_hour": "NAT gateway hour", "ipv4_idle": "Public IPv4 address, idle", "ipv4_in_use": "Public IPv4 address, in use", "vpce_gb": "VPC interface endpoint data processed", "vpce_hour": "VPC interface endpoint hour", "logs_ingest_std": "CloudWatch Logs ingestion, Standard class", "logs_ingest_ia": "CloudWatch Logs ingestion, Essentials (Infrequent Access) class", "logs_storage": "CloudWatch Logs storage", "s3_sia": "S3 Standard-IA storage", "s3_gir": "S3 Glacier Instant Retrieval storage", "s3_sia_retrieval": "S3 Standard-IA retrieval", "s3_gir_retrieval": "S3 Glacier Instant Retrieval retrieval", "s3_int_ia": "S3 Intelligent-Tiering, infrequent tier", "dt_inter_az": "Data transfer between availability zones", "eks_extended_hour": "EKS extended support", "eks_cluster_hour": "EKS cluster", "alb_hour": "Application Load Balancer hour", "clb_hour": "Classic Load Balancer hour", "nlb_hour": "Network Load Balancer hour", "opensearch_extended_nih": "OpenSearch Service Extended Support", } def rate_label(key, v): if key in LABELS: return LABELS[key] if key.startswith("rds_es:"): band, eng = key.split(":")[1], key.split(":")[-1] m = re.match(r"([A-Za-z]+)([0-9.]+)$", eng) eng = f"{m.group(1)} {m.group(2)}" if m else eng years = band.replace("Yr1-Yr2", "years 1 and 2").replace("Yr3", "year 3") return f"RDS Extended Support, {eng}, {years}" if key.startswith("rds:"): return v.get("desc", key) if key.startswith("ec2:"): _, t, what = key.split(":") return f"{t}, Linux, " + {"On-Demand": "On-Demand", "SP1": "Compute Savings Plan, 1 year, No Upfront", "SP3": "Compute Savings Plan, 3 years, No Upfront"}[what] return v.get("desc", key) def fmt_range(lo, hi): if yr(lo) == yr(hi): return yr(hi) return f"{yr(lo)} to {yr(hi)}" def fee_line(findings, fee, label=""): """The five-times promise: the fee is waived when the low ends of all findings, those that need a check included, add up to less than five times the fee a year. Says which way this memo falls.""" fee_txt = f"{label} (about {money(fee)})" if label else money(fee) n = len(findings) if not n: return f"Fee check: the checks found no savings to count, so there is no fee for this memo (the {fee_txt} audit fee is waived)." lo = sum(f.low for f in findings) nchk = sum(1 for f in findings if f.basis == "check") mult = lo / fee times = f"{mult:.0f}" if mult >= 10 else f"{math.floor(mult * 10) / 10:.1f}" which = (f"all {n} findings" if n != 1 else "the one finding") + ( f" (including the {nchk} that need{'s' if nchk == 1 else ''} a check)" if nchk and n != 1 else (" (it needs a check)" if nchk else "")) head = f"Fee check: the low ends of {which} add up to {yr(lo)} a year, {times} times the {fee_txt} audit fee" if mult >= 5: return head + ", so the fee applies. It is waived when that figure is under five times the fee." return head + ". That's under five times the fee, so there is no fee for this memo." def region_name(reg): return f"a region with usage-type prefix {reg[7:]}" if reg.startswith("prefix:") else reg def gaps(b, R): """What this memo couldn't price, said up front so nobody reads a total as complete when it isn't.""" out = [] for reg in sorted(R.missing): out.append(f"AWS's prices for {region_name(reg)} weren't loaded for this memo, so the {money(b.regions.get(reg, 0.0))} of usage billed " f"there is left out of every finding that compares against another price (Savings Plan, reservations, previous generation, gp3, " f"log class, S3 storage classes). Findings worked out from the bill's own charges include it.") for (what, reg), (n, cost, types) in sorted(R.unpriced.items()): if what == "rds-ri" and reg not in R.missing: out.append(f"{n} database instance{'s' if n != 1 else ''} in {reg} that ran all period ({money(cost)}: {', '.join(sorted(types))}) " f"{'are' if n != 1 else 'is'} left out of the reservation finding, because the loaded price list has no reserved price for " f"{'them' if n != 1 else 'it'}.") return out def render(b, R, findings, args): adj = 1 - b.discount_ratio tot_lo = sum(f.low for f in findings) tot_hi = sum(f.high for f in findings) bill_lo = sum(f.low for f in findings if f.basis == "bill") bill_hi = sum(f.high for f in findings if f.basis == "bill") chk_lo, chk_hi = tot_lo - bill_lo, tot_hi - bill_hi yearly_spend = b.spend * b.year period = (f"{b.start:%-d %B %Y} to {(b.end - dt.timedelta(seconds=1)):%-d %B %Y}" if b.start and b.end else "unknown period") fmts = ", ".join(sorted(b.formats)) title = f"AWS savings memo: {args.company}" p = [] p.append(f'') if args.sample: p.append('') p.append(f"{esc(title)}{' (sample)' if args.sample else ''} · Dwarka Point") p.append('') p.append('' '') if args.sample: p.append(PLAUSIBLE) p.append(f"
") p.append(f'

Dwarka Point Technologies · AWS bill audit{" · sample" if args.sample else ""}

') p.append(f"

{esc(title)}

") p.append(f'

Bill period {esc(period)} · {esc(fmts)}, {b.granularity}, {b.rows:,} line items' f'{", " + str(len(b.accounts)) + " account" + ("s" if len(b.accounts) != 1 else "") if b.accounts else ""} · prepared {esc(args.prepared)}

') if args.sample: p.append('' if args.bill_link else '') for g in gaps(b, R): p.append(f'') # summary p.append("

Summary

") p.append('
' f'
{money(b.spend)}
spent in this bill ({round(b.hours / 24)} days, before credits and tax), about {yr(yearly_spend)} a year
' f'
{fmt_range(tot_lo, tot_hi)}
a year in savings found ({tot_lo / yearly_spend * 100:.0f}% to {tot_hi / yearly_spend * 100:.0f}% of spend)
' f'
{fmt_range(bill_lo, bill_hi)}
of it shown by the bill alone; the rest needs a short check by your team
') lines = (f"The analyzer read every line item and ran {len(CHECKS)} checks; they found {len(findings)} changes worth making, below, largest first within each kind. " f"From the bill means the bill and AWS's price list prove the saving, and the change is known. " f"Needs a check means the cost is real but how much of it can go depends on something only your team can see; " f"each says what to look at.") p.append(f"

{lines}

") if b.credits > 1: p.append(f'

AWS credits covered {money(b.credits)} of this bill. Credits run out, so the figures below are worked out on usage before credits.

') if b.discount_ratio > 0.001: p.append(f'

The bill shows an enterprise or private-pricing discount of about {b.discount_ratio * 100:.1f}% of usage; every figure below is already reduced by it.

') rows = [] for i, f in enumerate(findings, 1): tag = f'{"From the bill" if f.basis == "bill" else "Needs a check"}' rows.append([f'{i}. {esc(f.title)}
{tag}{esc(f.effort)}', fmt_range(f.low, f.high)]) p.append(table(["Finding", "Saving a year"], rows, numeric={1}, idcol=False, raw={0})) if args.fee: p.append(f'

{esc(fee_line(findings, args.fee, getattr(args, "fee_label", "")))}

') # findings p.append("

Findings, largest first

") for i, f in enumerate(findings, 1): p.append(f'

{i}.{esc(f.title)}

' f'
{fmt_range(f.low, f.high)} a year
') p.append(f'

{"From the bill" if f.basis == "bill" else "Needs a check"}Effort: {esc(f.effort)}' + (f" · Now costs about {yr(f.now)} a year" if f.now else "") + "

") p.append(f"

{esc(f.summary)}

") p.append(f'

The change. {esc(f.action)}

') num = {i for i, c in enumerate(f.cols) if c in ("Cost", "Usage", "Hours", "Instances", "Size", "On-Demand cost", "Share", "On-Demand", "1-yr plan rate", "1-yr discount", "3-yr discount", "gp2", "gp3", "Saving a year", "Standard storage", "GET requests a month", "GETs per GB", "Ingested", "Now", "1-yr reserved", "3-yr reserved", "vCPUs billed each hour")} p.append(f'

The line items it rests on (summed over the bill period):

') p.append(table(f.cols, f.rows, numeric=num, tclass="ev")) p.append(f'

How the range is built. {esc(f.assumption)}

') p.append(f'

Check it yourself. {esc(f.verify)}

') nts = notes(b, R) if nts: p.append("

Also worth a look (not counted)

    " + "".join(f"
  • {n}
  • " for n in nts) + "
") p.append("

What the bill can't show

A billing export shows what was charged, not how things are used. These are the usual savings it " "can't see, each with a read-only way to check it in a few minutes:

    ") for t, why, how in CANT_SEE: p.append(f"
  • {esc(t)}: {esc(why)}. {esc(how)}
  • ") p.append("
") # method p.append("

Method and limits

") ranked = [(k, v) for k, v in sorted(b.svc.items(), key=lambda kv: -kv[1]) if v > 0.005] svc_rows = [[SERVICE_NAMES.get(k, k), money(v), f"{v / b.spend * 100:.1f}%"] for k, v in ranked[:9]] if len(ranked) > 9: rest = sum(v for _, v in ranked[9:]) svc_rows.append([f"Everything else ({len(ranked) - 9} services)", money(rest), f"{rest / b.spend * 100:.1f}%"]) p.append(f"

What was read. {b.rows:,} line items from {len(b.files)} file{'s' if len(b.files) != 1 else ''} ({esc(fmts)}, {b.granularity} granularity), " f"covering {esc(period)}. Yearly figures scale the bill period to 365 days ({b.year:.2f} times). Where the money went:

") p.append(table(["Service", "Cost", "Share"], svc_rows, numeric={1, 2}, idcol=False)) p.append("

Rates. Every rate comes from AWS's public price list (On-Demand list prices in USD), read on " f"{esc(R.d['generated'][:10])}. The rate code is the price list's own key (SKU, offer term, price dimension), so any line can be looked up. " "Where the bill carries its own public On-Demand rate, the bill's rate is used for the current cost.

") rrows = [] for (region, key), v in sorted(R.used.items(), key=lambda kv: (kv[0][0], rate_label(kv[0][1], kv[1]))): src = R.d["sources"].get(v.get("src"), {}) if v.get("parts"): # a 3-year Partial Upfront price: both parts and both codes, so each can be looked up rrows.append([rate_label(key, v), region, f"{price(v['usd'])} per {v.get('unit', '')} ({v['parts']})", f"{v.get('code', '')} (hourly part); {v.get('code2', '')} (upfront)", (src.get("published") or "")[:10]]) continue rrows.append([rate_label(key, v), region, price(v["usd"]) + " per " + v.get("unit", ""), v.get("code", ""), (src.get("published") or "")[:10]]) srcs = sorted({v.get("src") for v in R.used.values() if v.get("src")}) p.append(f"
The {len(rrows)} rates this memo uses, with their AWS rate codes") p.append(table(["Rate", "Region", "Price", "Rate code", "Published"], rrows, idcol=False)) p.append("

Price files: " + "; ".join(f'{esc(R.d["sources"][s]["title"])}' for s in srcs if s in R.d["sources"]) + ".

") p.append("

Limits. Savings use public list prices; if you have private pricing that doesn't appear in the bill, real savings scale down by " "that discount. Ranges are yearly and assume today's usage continues. Where two findings touch the same resources, each resource is counted " "in one of them only (the Savings Plan floor leaves out instances that other findings move or switch off, previous-generation instances " "tagged non-production count only as non-production, and idle NAT gateways only as idle), so the total doesn't count a dollar twice. " "Each alternative is priced for the region the resource runs in; a region whose prices weren't loaded is flagged at the top, never priced " "as another region. Nothing here is a change to your account: the analyzer reads a file, and your team decides every change.

") if args.sample: p.append(SAMPLE_CTA) p.append('') p.append("
") return "\n".join(p) SAMPLE_CTA = """

Get this memo for your own AWS bill

What you send: one month of billing data, with no access to your AWS account. Either the Cost and Usage Report you may already export (CUR 2.0 or legacy, CSV or Parquet), or, if you don't have one, a Cost Explorer download: Cost Explorer, Group by Usage type, Granularity Daily, the last full month, then Download as CSV. That takes about two minutes; the report gives a more detailed memo because it names each resource (when resource IDs are switched on in the export).

How: attach it to an email to contact@dwarkapoint.com, or share a link from your own storage that you can revoke. You can delete the account-name and tag columns first; the memo works without them, except the check for non-production machines, which reads the env tag.

What you get: a memo like this one within 48 hours, and an answer to any question about it. The data is used only for your memo and deleted once it's delivered; we'll confirm by email.

Price: $1,000 (₹85,000 in India), paid after you have the memo. If the memo finds less than five times the fee in yearly savings, counting the low end of each range, including findings that need a short check by your team, you pay nothing. If you want help making the changes afterwards, that's 20% of the savings realised over the first six months, nothing up front, and optional.

How the audit works

""" def run(paths, args): b = Bill() for pth in paths: for fmt, fname, r in read_rows(pth): b.add(fmt, fname, r) if not b.rows: sys.exit("no line items read") b.finish() R = Rates(args.rates) findings = [] for chk in CHECKS: try: findings += chk(b, R) except Exception as e: # one broken check must not sink the memo print(f"warning: {chk.__name__} failed: {e!r}", file=sys.stderr) if args.strict: raise adj = 1 - b.discount_ratio for f in findings: f.low *= adj f.high *= adj findings = [f for f in findings if f.high >= args.min_yearly] findings.sort(key=lambda f: (f.basis != "bill", -f.low, -f.high)) return b, R, findings def main(argv=None): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("bills", nargs="+") ap.add_argument("-o", "--out", default="memo.html") ap.add_argument("--company", default="your company") ap.add_argument("--prepared", default=dt.date.today().strftime("%-d %B %Y")) ap.add_argument("--rates", default=os.path.join(HERE, "rates.json")) ap.add_argument("--fee", type=float, default=0, help="audit fee in USD, for the fee-check line") ap.add_argument("--fee-label", default="", help='the fee as the buyer was quoted it, e.g. "₹85,000" (shown with the USD figure)') ap.add_argument("--min-yearly", type=float, default=200, help="drop findings worth less than this a year") ap.add_argument("--sample", action="store_true", help="sample page: banner, noindex, analytics, closing section") ap.add_argument("--bill-link", default="", help="sample page: link to the bill it was made from") ap.add_argument("--json", help="also write the findings as JSON here") ap.add_argument("--strict", action="store_true", help="stop on the first failing check") args = ap.parse_args(argv) b, R, findings = run(args.bills, args) with open(args.out, "w") as f: f.write(render(b, R, findings, args)) if args.json: with open(args.json, "w") as f: json.dump({"total": b.total, "hours": b.hours, "year_factor": b.year, "granularity": b.granularity, "findings": [{"key": x.key, "title": x.title, "basis": x.basis, "low": round(x.low, 2), "high": round(x.high, 2)} for x in findings]}, f, indent=1) lo, hi = sum(x.low for x in findings), sum(x.high for x in findings) print(f"{b.rows:,} line items, {money(b.total)} over {b.hours / 24:.0f} days; {len(findings)} findings, {yr(lo)} to {yr(hi)} a year -> {args.out}", file=sys.stderr) known = sorted(r for r in R.missing if not r.startswith("prefix:")) if known: print(f"WARNING: no prices loaded for {', '.join(known)}; the memo flags it. Before sending: " f"python3 analyzer/fetch_rates.py --regions {','.join(known)} (adds them to rates.json), then re-run.", file=sys.stderr) for g in gaps(b, R): print("WARNING: " + g, file=sys.stderr) for i, x in enumerate(findings, 1): print(f" {i:2d}. {fmt_range(x.low, x.high):>22} [{x.basis}] {x.title}", file=sys.stderr) if __name__ == "__main__": main()