#!/usr/bin/env bash # unused-ri-check.sh (CostFinch, https://costfinch.com/blog/reduce-rds-costs) # # What your unused Reserved Instances cost: every reservation with unused # hours across RDS, Aurora, ElastiCache, Redshift, OpenSearch and MemoryDB, # what it wasted last month, and what it will still waste before it expires. # # READ-ONLY. The only AWS call it makes is ce:GetReservationUtilization # (Cost Explorer). Nothing is written, changed, tagged or sent anywhere else. # The AWS managed ReadOnlyAccess policy covers it. # # Run it in the payer (management) account to see every account in the # organization. From a member account you only see that account. # Cost Explorer bills $0.01 per API call; one run makes about 10 to 15 calls. # # Usage, in AWS CloudShell: # curl -sO https://costfinch.com/tools/unused-ri-check.sh # less unused-ri-check.sh # read it first # bash unused-ri-check.sh # INCLUDE_EC2=1 bash unused-ri-check.sh # EC2 reservations too # # Output: a 3 month summary per service, one row per wasted reservation, and # a CSV in your home folder (CloudShell: Actions > Download file). # # "Wasted" is Cost Explorer's RICostForUnusedHours: the cost of reserved hours # that no running instance used. Seen from the payer account, discount sharing # is already applied, so these hours found no match in any account with # sharing turned on. Accounts with sharing turned off may still have matching # on-demand usage: that part is recoverable by turning sharing on. # # MIT License. Copyright (c) 2026 CostFinch. set -u THIS=$(date +%Y-%m-01) LAST=$(date -d "$THIS -1 month" +%F) START=$(date -d "$THIS -3 month" +%F) OUT=$(mktemp -d) SERVICES=( "Amazon Relational Database Service" "Amazon ElastiCache" "Amazon Redshift" "Amazon OpenSearch Service" "Amazon MemoryDB" ) [ "${INCLUDE_EC2:-0}" = "1" ] && SERVICES+=("Amazon Elastic Compute Cloud - Compute") i=0 for SVC in "${SERVICES[@]}"; do echo "Reading $SVC ..." >&2 echo "$SVC" > "$OUT/$i.name" F=$(printf '{"Dimensions":{"Key":"SERVICE","Values":["%s"]}}' "$SVC") # 1. Monthly totals, last 3 full months if aws ce get-reservation-utilization --region us-east-1 \ --time-period "Start=$START,End=$THIS" --granularity MONTHLY \ --filter "$F" --output json > "$OUT/$i.monthly" 2>"$OUT/$i.err"; then # 2. One row per reservation, last full month TOKEN=""; p=0 while :; do EXTRA=(); [ -n "$TOKEN" ] && EXTRA=(--next-page-token "$TOKEN") aws ce get-reservation-utilization --region us-east-1 \ --time-period "Start=$LAST,End=$THIS" \ --group-by Type=DIMENSION,Key=SUBSCRIPTION_ID \ --filter "$F" --output json "${EXTRA[@]}" > "$OUT/$i.ri.$p" 2>>"$OUT/$i.err" || break TOKEN=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1])).get("NextPageToken") or "")' "$OUT/$i.ri.$p") p=$((p+1)); [ -z "$TOKEN" ] && break done else rm -f "$OUT/$i.monthly" fi i=$((i+1)) done python3 - "$OUT" "$HOME/ri_waste_$LAST.csv" <<'PY' import csv, datetime as dt, glob, json, os, sys out, csv_path = sys.argv[1], sys.argv[2] SHORT = {"Amazon Relational Database Service": "RDS", "Amazon ElastiCache": "ElastiCache", "Amazon Redshift": "Redshift", "Amazon OpenSearch Service": "OpenSearch", "Amazon MemoryDB": "MemoryDB", "Amazon Elastic Compute Cloud - Compute": "EC2"} num = lambda x: float(x) if x not in (None, "") else 0.0 today = dt.date.today() monthly, rows, notes, months = {}, [], [], set() i = 0 while os.path.exists(f"{out}/{i}.name"): svc = SHORT.get(open(f"{out}/{i}.name").read().strip(), "?") err = open(f"{out}/{i}.err").read() if os.path.exists(f"{out}/{i}.err") else "" if not os.path.exists(f"{out}/{i}.monthly"): notes.append(f"{svc}: no reservations" if "DataUnavailable" in err else f"{svc}: error: {err.strip()[:160]}") i += 1 continue m = json.load(open(f"{out}/{i}.monthly")) monthly[svc] = {} for u in m.get("UtilizationsByTime", []): mon = u["TimePeriod"]["Start"][:7] months.add(mon) monthly[svc][mon] = (num(u["Total"].get("RICostForUnusedHours")), u["Total"].get("UtilizationPercentage", "")) for fp in sorted(glob.glob(f"{out}/{i}.ri.*")): try: d = json.load(open(fp)) except Exception: continue for u in d.get("UtilizationsByTime", []): for g in u.get("Groups", []): a = {k.lower(): v for k, v in (g.get("Attributes") or {}).items()} ut = g.get("Utilization", {}) waste = num(ut.get("RICostForUnusedHours")) if waste < 1: continue end = (a.get("enddatetime") or "")[:10] try: left = max(0.0, (dt.date.fromisoformat(end) - today).days / 30.44) except ValueError: left = 0.0 rows.append(dict(service=svc, account=a.get("accountid", ""), account_name=a.get("accountname") or "", region=a.get("region", ""), type=a.get("instancetype", ""), count=a.get("numberofinstances", ""), util=ut.get("UtilizationPercentage", ""), unused_hours=num(ut.get("UnusedHours")), waste_month=waste, ends=end, months_left=round(left, 1), waste_to_end=round(waste * left, 2), subscription=g.get("Value", ""))) i += 1 months = sorted(months) print("\nUNUSED RESERVATION COST, USD (cost of reserved hours nothing used)\n") print(f"{'Service':<12}" + "".join(f"{m:>12}" for m in months) + f"{'3 mo total':>13}{'Util% last':>12}") grand = [0.0] * len(months) for svc, vals in monthly.items(): line = [vals.get(m, (0.0, ""))[0] for m in months] grand = [x + y for x, y in zip(grand, line)] util = vals.get(months[-1], (0, ""))[1] if months else "" print(f"{svc:<12}" + "".join(f"{v:>12,.0f}" for v in line) + f"{sum(line):>13,.0f}{util:>12}") print(f"{'TOTAL':<12}" + "".join(f"{v:>12,.0f}" for v in grand) + f"{sum(grand):>13,.0f}") for n in notes: print(" " + n) rows.sort(key=lambda r: -r["waste_month"]) if rows: print(f"\nRESERVATIONS WITH UNUSED HOURS, {months[-1] if months else 'last month'} (most waste first)\n") print(f"{'Svc':<12}{'Account':<14}{'Region':<16}{'Type':<22}{'Qty':>4}{'Util%':>8}{'Wasted/mo':>11}{'Ends':>12}{'Waste to end':>14}") for r in rows[:40]: print(f"{r['service']:<12}{r['account']:<14}{r['region']:<16}{r['type'][:21]:<22}{str(r['count']):>4}" f"{str(r['util']):>8}{r['waste_month']:>11,.0f}{r['ends']:>12}{r['waste_to_end']:>14,.0f}") print(f"\nWasted last month: ${sum(r['waste_month'] for r in rows):,.0f} " f"Still to be wasted before these expire, if nothing changes: ${sum(r['waste_to_end'] for r in rows):,.0f}") with open(csv_path, "w", newline="") as fh: w = csv.DictWriter(fh, fieldnames=list(rows[0].keys())) w.writeheader() w.writerows(rows) print(f"Full list: {csv_path} (CloudShell: Actions > Download file)") else: print("\nNo reservation wasted more than $1 last month.") PY