Skip to main content

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.

✓ Cost Allocation Tags ✓ Savings Plans vs RIs ✓ Anomaly Detection ✓ Cost Explorer API

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
Environmentproduction, staging, devIdentify non-prod waste
Teamplatform, backend, dataChargeback / showback
Projectcheckout-v2, ml-pipelinePer-project cost tracking
CostCentercc-1042, cc-2011Finance reconciliation
AutoShutdowntrue, falseScheduled 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

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.

Share this tool: X / Twitter LinkedIn
✓ 60,000+ developers use DevPlaybook ★★★★★ 4.8 / 5 on Gumroad ✓ MIT licensed · Instant download ✓ No login required

Related Products

on Gumroad

You Might Also Need

More Free Tools

Enjoying this tool? Get more like it.

Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.

DevPlaybook Pro 7 days free

Unlock AI-Powered Dev Tools

  • ⚡ AI Code Review, Doc Generator & SQL Builder
  • ⚡ All premium templates & early access
  • ⚡ Member discounts on Gumroad products
Start Free Trial →

$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.

$79
$241 separately Save $162 (67% off)
Get DevPlaybook Pro — $79 →

MIT licensed · Instant download · No subscription

See what's included → Browse all deals →