AWS Cost Explorer Guide
Gain full visibility into your AWS spend with Cost Allocation Tags, Cost Anomaly Detection, and the Cost Explorer API. Cut costs by finding idle resources, rightsizing instances, and committing to Savings Plans with data.
Step 1 — Activate Cost Allocation Tags
Tags must be activated in the Billing console before they appear in Cost Explorer. Navigate to Billing → Cost allocation tags → AWS-generated tags and activate aws:createdBy. Then activate your user-defined tags.
# Tag enforcement via AWS Config rule (detect untagged resources)
aws configservice put-config-rule --config-rule '{
"ConfigRuleName": "required-tags",
"Source": {
"Owner": "AWS",
"SourceIdentifier": "REQUIRED_TAGS"
},
"InputParameters": "{\"tag1Key\":\"Environment\",\"tag2Key\":\"Team\",\"tag3Key\":\"Project\"}"
}'
# Tag all EC2 instances in a region using tag-editor (console) or CLI
aws ec2 describe-instances --query 'Reservations[*].Instances[*].InstanceId' \
--output text | xargs -I {} aws ec2 create-tags \
--resources {} \
--tags Key=Environment,Value=production Key=Team,Value=platform Recommended Tag Schema
| Tag Key | Example Values | Purpose |
|---|---|---|
| Environment | production, staging, dev | Identify non-prod waste |
| Team | platform, backend, data | Chargeback / showback |
| Project | checkout-v2, ml-pipeline | Per-project cost tracking |
| CostCenter | cc-1042, cc-2011 | Finance reconciliation |
| AutoShutdown | true, false | Scheduled stop/start |
Step 2 — Cost Anomaly Detection Setup
# Create a monitor for all AWS services
aws ce create-anomaly-monitor --anomaly-monitor '{
"MonitorName": "AllServicesMonitor",
"MonitorType": "DIMENSIONAL",
"MonitorDimension": "SERVICE"
}'
# Create an alert subscription (SNS + email)
aws ce create-anomaly-subscription --anomaly-subscription '{
"SubscriptionName": "DailyAnomalyAlert",
"MonitorArnList": ["arn:aws:ce::123456789012:anomalymonitor/MONITOR_ID"],
"Subscribers": [
{
"Address": "[email protected]",
"Type": "EMAIL"
},
{
"Address": "arn:aws:sns:us-east-1:123456789012:cost-alerts",
"Type": "SNS"
}
],
"Threshold": 100,
"Frequency": "DAILY"
}' Step 3 — Savings Plans Purchase via CLI
# View Savings Plan recommendations
aws savingsplans describe-savings-plans-offering-rates \
--savings-plan-offering-ids <offering-id> \
--filters '[{"name":"tenancy","values":["Shared"]}]'
# Get hourly commitment recommendation for 1-year Compute Savings Plan
aws ce get-savings-plans-purchase-recommendation \
--savings-plans-type COMPUTE_SP \
--term-in-years ONE_YEAR \
--payment-option NO_UPFRONT \
--lookback-period-in-days SIXTY_DAYS
# Purchase a Savings Plan ($10/hour commitment, 1-year, no upfront)
aws savingsplans create-savings-plan \
--savings-plan-offering-id <offering-id> \
--commitment 10.00 \
--client-token "purchase-$(date +%s)" Step 4 — Cost Explorer API Automation
import boto3
from datetime import datetime, timedelta
import json
ce = boto3.client('ce', region_name='us-east-1')
def get_daily_cost_by_team(days=30):
end = datetime.today().strftime('%Y-%m-%d')
start = (datetime.today() - timedelta(days=days)).strftime('%Y-%m-%d')
response = ce.get_cost_and_usage(
TimePeriod={'Start': start, 'End': end},
Granularity='DAILY',
Filter={
'Tags': {
'Key': 'Environment',
'Values': ['production']
}
},
GroupBy=[{'Type': 'TAG', 'Key': 'Team'}],
Metrics=['UnblendedCost']
)
return response['ResultsByTime']
# Get top services by cost this month
def get_top_services():
today = datetime.today()
start = today.replace(day=1).strftime('%Y-%m-%d')
end = today.strftime('%Y-%m-%d')
response = ce.get_cost_and_usage(
TimePeriod={'Start': start, 'End': end},
Granularity='MONTHLY',
GroupBy=[{'Type': 'DIMENSION', 'Key': 'SERVICE'}],
Metrics=['UnblendedCost']
)
groups = response['ResultsByTime'][0]['Groups']
sorted_groups = sorted(groups,
key=lambda x: float(x['Metrics']['UnblendedCost']['Amount']),
reverse=True)
for g in sorted_groups[:10]:
print(f"{g['Keys'][0]}: ${float(g['Metrics']['UnblendedCost']['Amount']):.2f}")
get_top_services() Monthly Cost Review Checklist
- Check Cost Anomaly Detection alerts from prior 30 days
- Review top 5 services by cost — any unexpected growth?
- Run EC2 rightsizing recommendations in Cost Explorer
- Check Savings Plan utilization — target >90%
- Identify untagged resources via AWS Config or Tag Editor
- Review idle RDS instances (0 connections over 7 days)
- Check S3 storage lens for buckets with no reads in 90 days
- Review NAT Gateway costs — often a surprise top-5 service
Frequently Asked Questions
How do Cost Allocation Tags actually reduce my AWS bill?▼
Cost Allocation Tags don't reduce your bill directly — they give you the visibility to find what's costing money and where. By tagging resources by team, project, environment, and service, you can see in Cost Explorer which team's Lambda functions are running all month, which staging environment was left on, or which S3 bucket is storing terabytes nobody uses. Without tags, you see a total bill; with tags you see a breakdown that makes rightsizing and shutdown decisions obvious. The savings come from acting on that data.
What is Cost Anomaly Detection and how do I set it up?▼
Cost Anomaly Detection is an AWS service that uses machine learning to detect unusual spending patterns and alert you via SNS or email. It establishes a baseline of your historical spend patterns and flags deviations above a threshold you configure (e.g., $100 or 20% above baseline). Set up a monitor for each service type or linked account, then create an alert subscription with a dollar threshold. It's free for the detection itself — you only pay for SNS/email delivery. It's far more useful than static budget alerts because it accounts for seasonal patterns.
When should I choose Reserved Instances vs Savings Plans?▼
Savings Plans are almost always the better choice for most workloads in 2026. Compute Savings Plans apply to EC2, Fargate, and Lambda across any region, instance family, OS, and tenancy — giving you flexibility to change instance types as you optimize. Reserved Instances require you to commit to a specific instance family and region. Use Reserved Instances when you have database workloads (RDS, Redshift, ElastiCache) that aren't covered by Savings Plans, or when you need capacity reservations in a specific AZ. For EC2 compute, start with Compute Savings Plans.
How do I use the Cost Explorer API to automate cost reporting?▼
The Cost Explorer API (aws ce get-cost-and-usage) lets you pull spend data programmatically by service, tag, account, and time range. Use it to build daily Slack reports, populate Grafana dashboards, or trigger alerts. Key parameters: TimePeriod (start/end dates), Granularity (DAILY/MONTHLY), Filter (by tag, service, account), GroupBy (dimension or tag key), and Metrics (BlendedCost, UnblendedCost, UsageQuantity). The API costs $0.01 per request after 100/month, so cache results aggressively. Use the Python boto3 client or AWS CLI — the CLI is great for quick one-off queries.
Related Products
on GumroadPremium Workflow Pack
Production-grade workflows, architecture guides, and deployment scripts for teams that ship. 10 advanced CI/CD workflows (blue-green, canary, E2E, security), 5 architecture deep-dives, code review checklist, PR process guide, and 5 battle-tested Bash deployment scripts.
Buy on Gumroad →GitHub Actions CI/CD Templates Pack
12 production-ready GitHub Actions workflow templates covering Node.js, Python, Docker, multi-environment deployments, security scanning, and auto-changelog. Copy, paste, ship.
Buy on Gumroad →Developer Productivity Bundle
Stop rebuilding the same setup every project. 51 VSCode snippets, 40 Git aliases, 5 Docker Compose stacks, 5 GitHub Actions workflows, 5 README templates, and a dotfiles kit. Set up a professional dev environment in under an hour.
Buy on Gumroad →You Might Also Need
AWS CDK Infrastructure as Code Guide
Complete AWS CDK guide for TypeScript/Python IaC. Learn constructs (L1/L2/L3), stacks, CDK Pipelines, diff/deploy workflow, and comparison with Terraform and CloudFormation.
Open free tool →
AWS Cost Estimator
Estimate monthly AWS costs for EC2, RDS, S3, CloudFront, and Load Balancers. Interactive calculator with itemized breakdown.
Open free tool →
AWS IAM Policy Generator
Visual AWS IAM policy JSON builder with action and resource selectors. Generate least-privilege IAM policies for S3, EC2, Lambda, DynamoDB, and more.
Open free tool →
More Free Tools
Related Articles
FinOps Engineering: A Developer's Guide to Cloud Cost Optimization in 2026
A practical guide to FinOps for engineers: AWS, GCP, and Azure cost tools, Infracost for Terraform, right-sizing, spot instances, reserved capacity, auto-scaling, and the FinOps maturity model. With code examples for CI/CD cost gates.
Cloud Cost Optimization in 2026: Strategies, Tools, and Real-World Savings
Cut your cloud bill without cutting performance. This practical guide covers FinOps practices, cost allocation, resource optimization, reserved capacity strategies, and the tools that help engineering teams understand and reduce cloud spend.
FinOps for Kubernetes: Cut Cloud Costs by 40% Without Slowing Engineering
Practical FinOps strategies for Kubernetes in 2026. Use Kubecost, KEDA, spot instances, and right-sizing to reduce cloud bills by 40% while maintaining performance.
AWS CDK with TypeScript: Build Cloud Infrastructure as Code
Learn AWS CDK with TypeScript from scratch. Understand constructs, stacks, L1/L2/L3 levels, testing, and deployment patterns for production-grade cloud infrastructure.
Pulumi vs Terraform 2026: Which IaC Tool Should You Choose?
A deep comparison of Pulumi and Terraform for infrastructure as code in 2026. Covers syntax, state management, provider ecosystem, team adoption, and when to choose each tool.
Enjoying this tool? Get more like it.
Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.
Unlock AI-Powered Dev Tools
- ⚡ AI Code Review, Doc Generator & SQL Builder
- ⚡ All premium templates & early access
- ⚡ Member discounts on Gumroad products
$9/mo after trial · Cancel anytime
Want the full toolkit?
Get DevPlaybook Pro
Every template, guide, boilerplate, and automation script in one bundle. 13 premium products — grab them all at once and save big.
MIT licensed · Instant download · No subscription
See what's included → Browse all deals →