AWS Cost Explorer: top spend → gemini analysis
Last 30 days of spend broken down by service, fed to gemini for a 'what changed' read. Run on the first of every month.
Setup
- → brew install awscli
- → aws configure
- → IAM: ce:GetCostAndUsage permission
- → GEMINI_API_KEY in env
Cost per run
<$0.01
The one-liner
$ START=$(date -u -v-30d +%Y-%m-%d 2>/dev/null || date -u -d '-30 days' +%Y-%m-%d)
END=$(date -u +%Y-%m-%d)
aws ce get-cost-and-usage \
--time-period Start=$START,End=$END \
--granularity MONTHLY --metrics BlendedCost \
--group-by Type=DIMENSION,Key=SERVICE \
| jq -r '.ResultsByTime[].Groups[] |
"\((.Metrics.BlendedCost.Amount | tonumber | floor))\t\(.Keys[0])"' \
| sort -rn | head -15 \
| gemini -m gemini-3.1-pro-preview -p \
"30-day AWS spend by service (USD, descending). In 4 sentences: which line is anomalously high vs the prior month's pattern, the likely cause, and one concrete action to investigate. No preamble."What each stage does
- [01] bash
date -u -v-30d OR date -u -d '-30 days'macOS BSD `date` uses -v relative offsets; Linux GNU `date` uses -d. The `||` fallback works on both. - [02] aws
aws ce get-cost-and-usage --group-by Type=DIMENSION,Key=SERVICECost Explorer's killer query: group by service. Other useful Keys: USAGE_TYPE, OPERATION, AZ, REGION, LINKED_ACCOUNT. - [03] jq
jq -r '… | (.Metrics.BlendedCost.Amount | tonumber | floor) …'Cost Explorer returns Amount as a STRING. tonumber + floor gets you whole-dollar integers for sorting. - [04] gemini
gemini -m gemini-3.1-pro-preview -p "…"gemini analyzes the cost table. The prompt asks specifically for 'anomalously high vs prior month' to push past 'EC2 is your biggest line' style obvious takes.
Expected output (sample)
AmazonEC2 is anomalously high at $1,847 (avg prior 90 days: ~$1,150). Likely cause: 3 c6i.xlarge reprocess-worker instances launched on 2026-04-23 and never terminated after the backfill completed. Action: aws ec2 describe-instances --filters 'Name=tag:Project,Values=reprocess' to confirm, then terminate the trio.
Caveats & tips
- Cost Explorer API itself costs $0.01 per request — not free. Use sparingly.
- IAM permission needed: ce:GetCostAndUsage. Most engineers don't have it by default.