180 AWS cost checks with Compute Optimizer ML integration, data transfer analysis, and reservation purchase recommendations

version
2.1.0
GitHub stars
24

Install

/plugin install aws-cost-saver@aws-cost-saver-marketplace

Run it inside Claude Code after adding the marketplace with /plugin marketplace add prajapatimehul/claude-aws-cost-saver.

Contents

Discovered from source

Skills 2

Reviewing AWS Cost Findings

Multi-perspective review of cost optimization findings with confidence-based filtering.

Quick Start

# Review findings and update findings.json in place
python3 "${CLAUDE_PLUGIN_ROOT}/skills/reviewing-findings/scripts/review_findings.py" findings.json --profile your-profile

# Re-review findings that already carry a review_status
python3 "${CLAUDE_PLUGIN_ROOT}/skills/reviewing-findings/scripts/review_findings.py" findings.json --force

For the detailed per-check confidence matrices and false-positive patterns, read REVIEW_CRITERIA.md in this skill's directory.

Review Process

1. Pre-flight Checks

Skip review if:

  • No findings.json exists
  • Findings already reviewed (has review_status)
  • Empty findings array

2. Multi-Agent Review (4 Parallel Agents)

Launch 4 independent review agents:

Agent #1: Resource Verification
├── Verify resource still exists
├── Check current utilization metrics
└── Confirm finding is still valid

Agent #2: Recommendation Quality
├── Validate recommendation is actionable
├── Check for edge cases (ASG, DR, scheduled)
└── Verify savings calculation logic

Agent #3: Business Context
├── Identify environment (prod/dev/staging)
├── Check for dependencies
└── Flag potential risks

Agent #4: Historical Pattern
├── Check for burst patterns
├── Identify seasonal usage
└── Review recent changes

3. Confidence Scoring

Each agent assigns confidence (0-100):

ScoreMeaning
90-100Definite savings - act immediately
70-89High confidence - safe to implement
50-69Medium confidence - needs validation
25-49Low confidence - likely false positive
0-24Skip - insufficient evidence

Filter threshold: 50 (adjustable)

4. Update Findings

Add review metadata to each finding:

{
  "check_id": "EC2-001",
  "monthly_savings": 150.00,
  "review_status": {
    "reviewed_at": "2026-01-19T15:00:00Z",
    "final_confidence": 85,
    "agents": {
      "resource_verification": 90,
      "recommendation_quality": 80,
      "business_context": 85,
      "historical_pattern": 85
    },
    "action": "approved",
    "notes": "Resource verified idle for 21 days"
  }
}

Review Criteria by Check Type

Idle Resources (EC2-001, RDS-001)

Verify:

  • CPU/memory metrics for 14+ days
  • Network activity
  • Not part of ASG or scheduled scaling
  • Not a standby/DR instance

Red flags:

  • Part of Auto Scaling Group → -30 confidence
  • Created < 14 days ago → -20 confidence
  • Has "dr" or "standby" in name → -25 confidence

Over-provisioned (EC2-002, RDS-002, LAMBDA-001)

Verify:

  • Peak utilization is below threshold
  • No recent high-utilization spikes
  • Recommended size handles peak + buffer

Red flags:

  • Peak CPU > 60% → -20 confidence
  • Burst workload pattern → -25 confidence
  • Memory not checked → -15 confidence

Unattached Storage (EC2-012, EBS-001)

Verify:

  • Volume truly unattached (not just unmounted)
  • No recent attachment activity
  • Not a backup volume

Red flags:

  • Detached < 7 days ago → -30 confidence
  • Has snapshot → lower urgency
  • Size > 500GB → verify with owner

Reserved Instance Coverage (RDS-005, RI-001)

Verify:

  • Workload is steady (not variable)
  • Commitment period acceptable
  • Instance type likely to remain same

Red flags:

  • Variable workload → -25 confidence
  • Pending migration → -40 confidence
  • Dev/test environment → -20 confidence

Agent Implementation

Agent #1: Resource Verification

Prompt: For each finding in findings.json, verify the resource:
1. Call AWS API to check resource exists
2. Get current utilization metrics (last 7 days)
3. Compare current state vs finding state
4. Score confidence based on verification

Output JSON with:
- resource_verified: boolean
- current_metrics: object
- confidence: 0-100
- notes: string

Agent #2: Recommendation Quality

Prompt: For each finding, evaluate the recommendation:
1. Is the recommendation actionable?
2. Are there edge cases not considered?
3. Is the savings calculation reasonable?
4. Are there dependencies to consider?

Score based on:
- Clear next steps: +20
- Edge cases addressed: +15
- Accurate savings: +25
- No dependencies: +20
- Reasonable effort: +20

Agent #3: Business Context

Prompt: For each finding, assess business context:
1. Identify environment (check name, tags)
2. Check for production dependencies
3. Assess risk of implementing recommendation
4. Consider compliance requirements

Adjust confidence:
- Production resource: -10 (needs careful review)
- Has dependencies: -20
- Compliance-related: -15
- Dev/test: +10 (lower risk)

Agent #4: Historical Pattern

Prompt: For each finding, analyze patterns:
1. Check CloudWatch metrics for patterns
2. Identify burst/scheduled workloads
3. Review resource modification history
4. Check for seasonal patterns

Red flags:
- Burst pattern detected: -25
- Recent scaling event: -20
- Seasonal variation: -15
- Consistent low usage: +15

Output Format

Terminal Output

## Findings Review

Reviewed 35 findings. Results:

✓ 25 findings APPROVED (confidence ≥70)
⚠ 6 findings NEEDS VALIDATION (confidence 50-69)
✗ 4 findings FILTERED (confidence <50)

### Top Approved Findings

1. **RDS-002**: Over-provisioned RDS Instance
   Resource: production-clinical-trial-matcher
   Savings: $95.00/month
   Confidence: 85%
   Notes: CPU avg 2.6% for 31 days, no burst patterns

2. **EC2-012**: Unattached EBS Volume
   Resource: vol-0f282561946f02d6a
   Savings: $8.00/month
   Confidence: 92%
   Notes: Unattached for 45 days, has snapshot backup

### Needs Validation

1. **LAMBDA-001**: Memory Over-provisioning
   Resource: production-file-handler
   Confidence: 55%
   Issue: Only 78 invocations - insufficient data
   Action: Monitor for 14 more days

### Filtered (False Positives)

1. **EC2-001**: Idle EC2 Instance
   Resource: i-0885726ca0d3e7856
   Original confidence: 75%
   Final confidence: 35%
   Reason: Part of ASG, scheduled scaling detected

Updated findings.json

Each finding gets a review_status object added.

Workflow

  1. Read findings.json
  2. Launch 4 parallel review agents (use Task tool)
  3. Collect agent results
  4. Calculate final confidence (average of 4 agents)
  5. Apply filter threshold (50)
  6. Update findings with review status
  7. Generate summary report
  8. Save updated findings.json

Task Checklist

- [ ] Load findings.json
- [ ] Launch Agent #1: Resource Verification
- [ ] Launch Agent #2: Recommendation Quality
- [ ] Launch Agent #3: Business Context
- [ ] Launch Agent #4: Historical Pattern
- [ ] Merge agent results
- [ ] Calculate final confidence scores
- [ ] Apply filter threshold
- [ ] Update findings with review_status
- [ ] Save updated findings.json
- [ ] Output summary to terminal

Validating AWS Pricing

MANDATORY validation step that catches pricing errors before they reach the user.

Why This Matters

Common errors this skill catches:

  • CloudWatch Logs: Confusing $0.50/GB ingestion with $0.03/GB storage
  • Savings exceeding actual service spend (impossible)
  • Wrong multipliers or formulas
  • Missing cost components

Purpose

This skill validates pricing for ALL findings using the Zero Hallucination Pricing System. Every finding must have a verifiable pricing_source. Findings without a pricing source or with fabricated prices are rejected (set to monthly_savings=0 with pricing_unknown=true).

Quick Start

# Validate with default $100 threshold (queries API only for >$100 findings)
python3 "${CLAUDE_PLUGIN_ROOT}/skills/validating-aws-pricing/scripts/validate_pricing.py" findings.json --profile your-profile

# Lower threshold to validate more findings
python3 "${CLAUDE_PLUGIN_ROOT}/skills/validating-aws-pricing/scripts/validate_pricing.py" findings.json --profile your-profile --threshold 50

# Works with any AWS auth method (SSO, access keys, IAM role)
python3 "${CLAUDE_PLUGIN_ROOT}/skills/validating-aws-pricing/scripts/validate_pricing.py" findings.json  # uses default credentials

What Gets Updated

For findings above threshold (default $100):

  1. Queries real AWS Pricing API for EC2, RDS, EBS
  2. Updates monthly_savings with validated value
  3. Marks api_validated: true in metadata

For findings below threshold:

  1. Preserves pricing that already carries a compliant pricing_source and calculation
  2. Resolves from the verified us-east-1 table where an exact formula exists
  3. Otherwise sets monthly_savings=0 with pricing_unknown=true — it NEVER estimates

All findings get pricing_validated metadata showing the source.

Pricing Calculation by Finding Type

Idle Resources (EC2-001, etc.)

Savings = Full monthly cost of the resource

savings = hourly_rate * 730  # Resource should be terminated

Unattached Storage (EC2-012, EBS-001)

Savings = Storage cost per month

savings = size_gb * price_per_gb  # e.g., 100GB * $0.08 = $8.00

Over-provisioned (RDS-002, LAMBDA-001)

Savings = Difference between current and recommended size

current_cost = current_hourly * 730
recommended_cost = recommended_hourly * 730
savings = current_cost - recommended_cost

No RI Coverage (RDS-005)

Savings = On-Demand cost - Reserved Instance cost

on_demand_monthly = hourly_rate * 730
ri_monthly = ri_upfront / 12 + ri_hourly * 730
savings = on_demand_monthly - ri_monthly  # ~40-60% typically

CloudWatch Logs (LOG-001)

Savings = Storage cost that can be avoided with retention policy

savings = stored_gb * 0.03  # $0.03 per GB-month

AWS Pricing Reference

Current pricing (us-east-1):

ResourcePriceUnitMonthly (730 hrs)
t2.nano$0.0058/hour$4.23
t3.nano$0.0052/hour$3.80
gp3 storage$0.08/GB-month-
db.r5.xlarge$0.50/hour$365.00
cache.t3.small (Valkey)$0.0272/hour$19.86
CloudWatch Logs$0.03/GB-month-

For complete pricing, see PRICING_REFERENCE.md.

Output

The script updates findings.json in place:

{
  "check_id": "EC2-001",
  "monthly_savings": 4.23,
  "pricing_validated": {
    "source": "AWS Pricing API",
    "validated_at": "2026-01-19T10:00:00Z",
    "hourly_rate": 0.0058,
    "calculation": "0.0058 * 730 hours"
  }
}

Workflow

  1. Load findings.json
  2. For each finding:
    • Identify resource type from check_id and details
    • Query AWS Pricing API (or use cached known prices)
    • Calculate correct savings based on finding category
    • Update monthly_savings field
    • Add pricing_validated metadata
  3. Recalculate total_monthly_savings in metadata
  4. Save updated findings.json

Task Checklist

- [ ] Load findings.json
- [ ] Get actual billing from Cost Explorer (by service AND usage type)
- [ ] ANTI-HALLUCINATION CHECKS (run first):
  - [ ] Every finding has details.pricing_source (reject if missing)
  - [ ] Every finding with savings > 0 has details.calculation (reject if missing)
  - [ ] No findings have savings > 0 with pricing_source="pricing_unknown" (reject if found)
  - [ ] No idle findings count missing metrics as zero activity (reject if found)
  - [ ] Downsize targets are same-family-one-size-down or from Compute Optimizer (reject if not)
- [ ] For EACH finding:
  - [ ] Verify formula matches finding type
  - [ ] Check savings <= service spend (sanity check)
  - [ ] Query AWS Pricing API for ALL findings with pricing_source != "aws_pricing_api"
  - [ ] Check OS matches (Windows vs Linux) for EC2 findings
  - [ ] Check deployment option matches (Multi-AZ vs Single-AZ) for RDS findings
  - [ ] Check all EBS components (storage + IOPS + throughput) for EBS findings
  - [ ] Recalculate if errors found
  - [ ] Add calculation breakdown to details
- [ ] Flag any corrected findings with pricing_corrected: true
- [ ] Set any unfixable findings to monthly_savings=0 with pricing_unknown=true
- [ ] Recalculate total savings in metadata
- [ ] Save corrected findings.json
- [ ] Regenerate report with accurate prices

CRITICAL: Sanity Check Rules

Rule 1: Savings Cannot Exceed Service Spend

assert finding.monthly_savings <= service_monthly_spend, \
    f"Finding {finding.check_id} claims ${finding.monthly_savings} but service only costs ${service_monthly_spend}"

Example Failure:

  • Finding: CloudWatch Logs retention saves $594/mo
  • Billing: CloudWatch total spend = $159/mo
  • INVALID - immediately flag and recalculate

Rule 2: Use Correct Cost Component

Many AWS services have MULTIPLE cost components:

ServiceComponentsWhat Retention Affects
CloudWatch LogsIngestion ($0.50/GB) + Storage ($0.03/GB)Storage ONLY
S3Storage + Requests + TransferStorage + old versions
EBSStorage + IOPS + ThroughputStorage ONLY
RDSCompute + Storage + I/ODepends on finding

Rule 3: Verify With Usage Type Breakdown

For any finding > $100, get usage-type breakdown:

aws ce get-cost-and-usage --profile {profile} \
  --time-period Start={LAST_MONTH_START},End={LAST_MONTH_END} \
  --granularity MONTHLY \
  --metrics UnblendedCost \
  --filter '{"Dimensions": {"Key": "SERVICE", "Values": ["AmazonCloudWatch"]}}' \
  --group-by Type=DIMENSION,Key=USAGE_TYPE

This shows:

  • DataProcessing-Bytes: Log ingestion ($0.50/GB)
  • TimedStorage-ByteHrs: Log storage ($0.03/GB)

Only storage can be reduced by retention policy!


Common Pricing Mistakes & Corrections

CloudWatch Logs Retention

WRONG:

savings = stored_gb * 0.50  # Using ingestion price!
# 221 GB * $0.50 = $110.50  # WRONG!

CORRECT:

savings = stored_gb * 0.03  # Storage price
# 221 GB * $0.03 = $6.63    # CORRECT!

Even more correct (check what % is older than retention):

# If setting 90-day retention, only logs older than 90 days are deleted
# Estimate 50% of stored data is older than 90 days
savings = stored_gb * 0.03 * 0.5

Unattached EBS Volume

CORRECT:

savings = size_gb * price_per_gb
# gp3: 100 GB * $0.08 = $8.00
# gp2: 100 GB * $0.10 = $10.00

Over-provisioned RDS

CORRECT:

current_cost = current_hourly * 730
recommended_cost = recommended_hourly * 730
savings = current_cost - recommended_cost

# db.r5.xlarge -> db.r5.large
# $0.50 * 730 - $0.25 * 730 = $365 - $182.50 = $182.50

Validation Output Format

After validation, each finding should include:

{
  "check_id": "LOG-001",
  "monthly_savings": 6.64,
  "pricing_validated": {
    "validated_at": "2026-01-19T12:00:00Z",
    "original_estimate": 594.34,
    "corrected": true,
    "correction_reason": "Used storage price ($0.03/GB) instead of ingestion price ($0.50/GB)",
    "calculation": "221.4 GB × $0.03/GB = $6.64",
    "sanity_check": {
      "service": "AmazonCloudWatch",
      "service_spend": 159.13,
      "finding_savings": 6.64,
      "passed": true
    }
  }
}

Commands 1

AWS Cost Optimization Scan

Step 0: Ask for AWS Profile

If a profile name was passed as an argument ($ARGUMENTS), use it and skip the question. Otherwise, ask the user which AWS profile to use:

{
  "questions": [{
    "header": "AWS Profile",
    "question": "Which AWS profile should I use for the scan?",
    "multiSelect": false,
    "options": [
      {"label": "default", "description": "Use default AWS credentials"},
      {"label": "Enter profile name", "description": "I'll type my profile name"}
    ]
  }]
}

If user selects "Enter profile name" or "Other", ask them to type the profile name.

Store the profile name for all subsequent AWS commands.

Authentication: AWS commands work with any valid AWS credentials:

  • SSO profile: --profile your-sso-profile
  • Named profile: --profile your-profile
  • Environment variables: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY
  • IAM role (EC2/Lambda): automatic

Step 1: Discover Account

aws sts get-caller-identity --profile {profile}

Extract:

  • Account ID → use in report header
  • Profile name → use for file naming: reports/findings_{profile}.json

Step 2: Find Active Regions

# Get all regions
aws ec2 describe-regions --profile {profile} --query 'Regions[].RegionName' --output json

# Check which have EC2 instances (quick check)
aws ec2 describe-instances --profile {profile} --query 'Reservations[].Instances[0].Placement.AvailabilityZone' --output text

Only scan regions with resources.

Step 3: Ask Compliance

Use AskUserQuestion:

{
  "questions": [{
    "header": "Compliance",
    "question": "Which compliance requirements apply?",
    "multiSelect": true,
    "options": [
      {"label": "HIPAA", "description": "Healthcare - skip PHI resources"},
      {"label": "SOC2", "description": "Audit - preserve all logs"},
      {"label": "PCI-DSS", "description": "Payments - skip payment infra"},
      {"label": "None", "description": "No compliance requirements"}
    ]
  }]
}

Step 3.5: Check Compute Optimizer + Cost Optimization Hub Enrollment

aws compute-optimizer get-enrollment-status --profile {profile}
aws cost-optimization-hub list-enrollment-statuses --region us-east-1 --profile {profile}

If Compute Optimizer status is Inactive, inform the user:

"AWS Compute Optimizer is not enabled. It provides free ML-powered rightsizing and idle detection. Enable with: aws compute-optimizer update-enrollment-status --status Active"

If Cost Optimization Hub is not enrolled, inform the user:

"Cost Optimization Hub is not enabled. It is free and aggregates deduplicated, discount-aware savings recommendations across all regions and accounts. Enable it in the Billing console or with: aws cost-optimization-hub update-enrollment-status --status Active --region us-east-1"

Store compute_optimizer_active and cost_optimization_hub_active in metadata. Pass both to domain agents.

Step 4: Get Actual Monthly Spend + Data Transfer Breakdown

CRITICAL: Query AWS Cost Explorer for real billing data.

# Service-level spend
aws ce get-cost-and-usage \
  --profile {profile} \
  --time-period Start={LAST_MONTH_START},End={LAST_MONTH_END} \
  --granularity MONTHLY \
  --metrics UnblendedCost \
  --group-by Type=DIMENSION,Key=SERVICE

NEW: Also query USAGE_TYPE for data transfer costs (same API, $0.01 extra):

# Data transfer breakdown (surfaces hidden costs)
aws ce get-cost-and-usage \
  --profile {profile} \
  --time-period Start={LAST_MONTH_START},End={LAST_MONTH_END} \
  --granularity MONTHLY \
  --metrics UnblendedCost \
  --group-by Type=DIMENSION,Key=USAGE_TYPE \
  --filter '{"Dimensions":{"Key":"SERVICE","Values":["Amazon Elastic Compute Cloud - Compute"]}}'

Store both actual_monthly_spend and data_transfer_breakdown in metadata.

Note: If no --profile is provided, AWS CLI uses default credentials (env vars or IAM role).

Step 4.5: Build a Spend-Led Scan Order

Do not treat all domains equally. Rank them from actual spend first.

If you are working inside a checkout of this repository (main.py exists in the project root), run:

python main.py spend-hotspots --profile {profile} --output reports/spend_hotspots_{profile}.md

Otherwise (marketplace install — main.py is not shipped with the plugin), build the same ranking directly from the Step 4 Cost Explorer output: order services by spend, then for each of the top 5 services query USAGE_TYPE breakdown (the same aws ce get-cost-and-usage call with a SERVICE filter) and map dominant usage types to check IDs using the Spend-Led Scan Order table in the subagent prompt.

If you need more EC2 detail and the account supports it, optionally query resource-level spend:

aws ce get-cost-and-usage-with-resources \
  --profile {profile} \
  --time-period Start={LAST_MONTH_START},End={LAST_MONTH_END} \
  --granularity MONTHLY \
  --metrics UnblendedCost \
  --filter '{"Dimensions":{"Key":"SERVICE","Values":["Amazon Elastic Compute Cloud - Compute"]}}'

Optional accelerators:

  • Cost Optimization Hub: use recommendations if available, but do not fail the scan if the service is disabled or returns nothing.
  • Public IP Insights: if IPAM is enabled, use it to inventory billable public IPv4 addresses before relying only on ENI or EIP inventory.

Step 5: Parallel Domain Scan

Launch 11 aws-cost-saver:aws-cost-saver subagents in parallel:

AgentDomainChecks
1computeEC2, EBS, AMIs, snapshots, EIPs, Compute Optimizer
2storageS3, EFS, CloudWatch Logs, CloudTrail, Secrets Manager
3databaseRDS, DynamoDB, ElastiCache
4networkingNAT, ELB, VPC endpoints, public IPv4, data transfer, Route 53
5serverlessLambda, API Gateway, SQS, Step Functions
6reservationsRI coverage, Savings Plans, purchase recommendations
7containersECS, EKS, Fargate, ECR
8advanced_databasesAurora, DocumentDB, Neptune, Redshift
9analyticsSageMaker, EMR, OpenSearch, QuickSight
10data_pipelinesKinesis, MSK, Glue, EventBridge
11storage_advancedFSx, AWS Backup

Pass to each:

  • region: Active region(s)
  • compliance: User's selection
  • profile: AWS profile name
  • compute_optimizer_active: Whether CO is enrolled (for compute domain)
  • data_transfer_breakdown: USAGE_TYPE costs (for networking domain)
  • spend_hotspots: Top services and usage types from Step 4.5

Step 6: Merge, Anti-Hallucination Check & Quick Review

Combine all 11 outputs into reports/findings_{profile}.json.

6.0: Anti-Hallucination Verification (MANDATORY)

The subagent SHOULD apply these rules internally. This step is a safety net to catch any violations that slipped through. Verify EVERY finding:

Check 1: pricing_source exists Every finding MUST have details.pricing_source set to one of:

  • aws_pricing_api — price from Pricing API
  • verified_table — price from hardcoded table (us-east-1 only)
  • aws_cost_explorer — price from Cost Explorer (RI/SP)
  • pricing_unknown — price not found, monthly_savings MUST be 0

If pricing_source is missing → REJECT, set monthly_savings=0, add pricing_unknown=true.

Check 2: calculation exists Every finding with monthly_savings > 0 MUST have details.calculation with formula and numbers. If missing → REJECT.

Check 3: No fabricated prices Any finding without pricing_source but with monthly_savings > 0 → set to 0 with pricing_unknown: true.

Check 4: No missing-data-as-zero Idle findings where any signal has "status": "no_data" but was counted as meeting threshold → recalculate idle score without that signal.

Check 5: Downsize targets are valid Over-provisioned findings must use Compute Optimizer target OR one size down in same family. Otherwise → set monthly_savings=0.

Check 6: RI/SP and Spot coverage noted Any EC2/RDS finding should have covered_by_ri_or_sp or instance_lifecycle in details if applicable. If missing for high-savings findings → flag for manual review.

Check 7: IaC-managed resources flagged Findings recommending deletion of resources with aws:cloudformation:stack-name or terraform tags should have managed_by_iac: true and adjusted recommendation.

Quick Review (inline - no scripts):

Apply 2 adjustments only:

  1. Resource Age: -30% confidence if created < 7 days ago
  2. Environment: -10% for production, +10% for dev/test (from Name tags)

Mark findings:

  • approved if confidence ≥ 70%
  • needs_validation if confidence 50-69%
  • filtered if confidence < 50%

Step 6.5: MANDATORY Price Validation

CRITICAL: Before generating the report, validate ALL pricing calculations.

6.5.1: Get Service-Level Billing

Query Cost Explorer for service breakdown:

aws ce get-cost-and-usage --profile {profile} \
  --time-period Start={LAST_MONTH_START},End={LAST_MONTH_END} \
  --granularity MONTHLY \
  --metrics UnblendedCost \
  --group-by Type=DIMENSION,Key=SERVICE

6.5.2: Sanity Check Each Finding

For EVERY finding, verify:

finding.monthly_savings <= service_monthly_spend

Example Check:

  • Finding: CloudWatch Logs savings = $594/mo
  • Billing: CloudWatch total = $159/mo
  • FAIL - Finding exceeds service spend!

6.5.3: Verify Calculation Formula

Each finding type has a SPECIFIC formula:

Finding TypeCorrect Formula
CW Logs Retentionstored_gb × $0.03 (storage only)
Unattached EBSsize_gb × price_per_gb
Idle EC2hourly_rate × 730
Over-provisionedcurrent_cost - recommended_cost
No RI Coverageon_demand_cost × savings_percent
Public IPv4 Chargesaddress_count × $0.005 × 730
Idle EKS Cluster(cluster_hourly_rate × 730) + node_costs
Idle Fargate TaskvCPU_hrs × $0.04048 + GB_hrs × $0.004445
Idle Aurorahourly_rate × 730 + storage_gb × $0.10
Idle Redshiftnode_hourly × nodes × 730
Idle SageMaker Endpointhourly_rate × 730
Over-provisioned Kinesisshards × $0.015/hr × 730
Idle MSK Clusterbroker_cost × brokers
NAT Data Processinggb_processed × $0.045
Cross-AZ Transfergb_transferred × $0.02 (both directions)
Unused Secretscount × $0.40
Unused Route 53 Zonecount × $0.50
EBS Snapshot Archivegb_months × ($0.05 - $0.0125)
RI Purchase SavingsFrom ce get-reservation-purchase-recommendation
SP Purchase SavingsFrom ce get-savings-plans-purchase-recommendation

6.5.4: Flag & Correct Invalid Findings

If a finding fails validation:

  1. Recalculate using correct formula
  2. Update monthly_savings with corrected value
  3. Add pricing_corrected: true to details
  4. Document the correction reason

6.5.5: Get Detailed Cost Breakdown (for >$100 findings)

For findings claiming >$100 savings, query usage type breakdown:

aws ce get-cost-and-usage --profile {profile} \
  --time-period Start={LAST_MONTH_START},End={LAST_MONTH_END} \
  --granularity MONTHLY \
  --metrics UnblendedCost \
  --filter '{"Dimensions": {"Key": "SERVICE", "Values": ["AmazonCloudWatch"]}}' \
  --group-by Type=DIMENSION,Key=USAGE_TYPE

This reveals actual storage vs ingestion costs.

Step 6.6: Calculate Priority Scores

Rank findings by actionability, not just savings amount.

Formula

priority_score = impact × confidence × urgency × risk_multiplier

Components

ComponentCalculationRange
Impactmin(monthly_savings / 100, 10)0.1 - 10
Confidenceconfidence / 1000.5 - 1.0
UrgencyBased on idle duration0.7 - 1.5
Risk MultiplierBased on environment0.5 - 1.5

Urgency Values

Idle DurationUrgency
> 30 days1.5
14-30 days1.2
7-14 days1.0
< 7 days0.7

Risk Multiplier Values

EnvironmentMultiplier
dev/test1.5 (lower risk)
staging1.0
production0.5 (higher risk)

Example

Finding: Idle RDS ($365/mo), 85% confidence, 21 days idle, production

impact = min(365/100, 10) = 3.65
confidence = 0.85
urgency = 1.2 (14-30 days)
risk = 0.5 (production)

priority_score = 3.65 × 0.85 × 1.2 × 0.5 = 1.86 (MEDIUM)

Priority Ranking

ScorePriorityAction
> 5.0CriticalThis week
2.0-5.0HighThis month
1.0-2.0MediumNext quarter
< 1.0LowWhen convenient

Step 7: Generate Report

Create reports/cost_report_{profile}.md:

# AWS Cost Optimization Report

**Account:** {account_id}
**Profile:** {profile}
**Date:** {scan_date}
**Compliance:** {compliance}

## Summary

| Metric | Value |
|--------|-------|
| Actual Monthly Spend | $X,XXX |
| Approved Savings | $XXX/mo |
| Needs Validation | $XX/mo |

## Quick Wins (Implement This Week)
...

## Top Savings Opportunities
...

## Needs Validation
...

Show user:

  1. Total approved savings
  2. Top 5 findings
  3. Ask which to implement

Agents 1

AWS Cost Optimization Scanner

Scan ONE domain for cost optimization findings.

Input

  • domain: compute | storage | database | networking | serverless | reservations | containers | advanced_databases | analytics | data_pipelines | storage_advanced
  • region: AWS region to scan
  • compliance: [HIPAA, SOC2, PCI-DSS] or empty
  • profile: AWS profile name
  • spend_hotspots: Optional Cost Explorer service and usage-type hotspots from the account-wide pre-scan
  • cost_optimization_hub_recommendations: Optional accelerator input if Cost Optimization Hub is enabled

11 Domains (180 checks total)

DomainChecksResources
compute28EC2, EBS, AMIs, snapshots, EIPs, Compute Optimizer, Cost Optimization Hub
storage24S3, EFS, CloudWatch Logs, CloudTrail, Secrets Manager
database17RDS (incl. extended support), DynamoDB, ElastiCache (incl. Valkey migration)
networking19NAT, ELB, VPC endpoints, public IPv4, data transfer, Route 53
serverless11Lambda, API Gateway, SQS, Step Functions
reservations13RI coverage, Savings Plans (incl. Database SP), purchase recommendations
containers17ECS, EKS (incl. extended support versions), Fargate, ECR
advanced_databases18Aurora, DocumentDB, Neptune, Redshift
analytics15SageMaker, EMR, OpenSearch, QuickSight
data_pipelines12Kinesis, MSK, Glue, EventBridge
storage_advanced6FSx, AWS Backup

Workflow

  1. Read the check definitions for your domain from ${CLAUDE_PLUGIN_ROOT}/checks/all_checks.yaml. If that variable is not expanded in your prompt, locate the file with Glob (**/aws-cost-saver/checks/all_checks.yaml) — it is bundled with this plugin.
  2. Start from Cost Explorer spend hotspots and prioritize the highest-cost services or usage types first
  3. Run AWS CLI commands via MCP tool
  4. Save resource inventory
  5. Compare against thresholds
  6. Return findings + resources

Spend-Led Scan Order

Do not scan purely from inventory. Use account-level spend context first:

  1. Read the top services from Cost Explorer
  2. For high-cost services, inspect top USAGE_TYPE rows before applying heuristics
  3. Prioritize checks that match the bill shape:
    • PublicIPv4* -> NET-018, NET-001
    • NatGateway* -> NET-016, NET-007, NET-002
    • DataTransfer-Regional-Bytes -> NET-004, NET-017
    • DataTransfer-Out-Bytes -> NET-005, NET-006, NET-008
    • Snapshot* -> EC2-009, RDS-007

If Cost Explorer returns a top-spend service but this domain produces no findings, explicitly note the blind spot in the output so the operator knows more manual review is needed.

Cost Optimization Hub (COH-001, preferred source)

Cost Optimization Hub is free and aggregates deduplicated, discount-aware recommendations across 25 resource types and all regions from a single us-east-1 endpoint:

aws cost-optimization-hub list-enrollment-statuses --region us-east-1
aws cost-optimization-hub list-recommendation-summaries --group-by ResourceType --region us-east-1
aws cost-optimization-hub list-recommendations --include-all-recommendations --region us-east-1
  • If enrolled, treat COH estimatedMonthlySavings as the authoritative number for resources it covers (rightsizing, idle, GP2→GP3, Graviton, RI/SP purchases) — its estimates already account for existing RI/SP discounts. Set pricing_source: "aws_cost_explorer" with a note "savings_provider": "cost_optimization_hub".
  • Keep running the plugin's own checks for what COH does NOT cover: EIPs, idle ELBs, snapshots, S3 lifecycle, CloudWatch Logs, ECR, Route 53, data transfer, Secrets Manager, CloudTrail, extended-support charges.
  • Do not fail the scan if COH is disabled or returns nothing.

Optional Accelerators

  • Use Public IP Insights when IPAM is enabled to inventory public IPv4 spend more completely across ENIs, EIPs, Global Accelerator, and VPN.

Compliance Rules

ComplianceRuleskip_reason
HIPAASkip phi=true tags, healthcare nameshipaa-protected
SOC2Don't delete logs (but CAN set retention)soc2-audit-required
PCI-DSSSkip pci=true tags, payment VPCspci-dss-protected

Tag-Based Exclusions

SkipCostOpt Tag

Resources with SkipCostOpt=true are excluded from ALL checks.

Exclusion Tags (Honor Any)

Tag KeyTruthy Values
SkipCostOpttrue, 1, yes
CostOptExcludetrue, 1, yes
DoNotOptimizetrue, 1, yes

Check Tags in Resource Data

# Tags included in describe-* responses
# Check Tags array for exclusion keys

Output When Excluded

{
  "resource_id": "i-abc123",
  "status": "excluded",
  "exclusion_reason": "Tag SkipCostOpt=true"
}

Output Format

{
  "domain": "compute",
  "region": "us-east-1",
  "scanned_at": "2026-01-19T15:00:00Z",
  "resources": {
    "ec2_instances": [...],
    "ebs_volumes": [...]
  },
  "resource_summary": {
    "total_resources": 17,
    "total_findings": 3
  },
  "findings": [
    {
      "check_id": "EC2-001",
      "resource_id": "i-abc123",
      "resource_name": "web-server-1",
      "title": "Idle EC2 Instance",
      "domain": "compute",
      "severity": "high",
      "category": "idle",
      "monthly_savings": 70.00,
      "confidence": 85,
      "description": "CPU < 5% for 14+ days",
      "recommendation": "Terminate or stop",
      "environment": "production",
      "skip_reason": null,
      "actionable": true,
      "details": {...}
    }
  ]
}

Resource Inventory by Domain

compute

  • ec2_instances: All instances
  • ebs_volumes: All volumes
  • elastic_ips: All EIPs
  • snapshots: Account snapshots
  • amis: Account AMIs
  • compute_optimizer_status: Enrollment status (Active/Inactive)
  • compute_optimizer_recommendations: CO recommendations (if enrolled)

storage

  • s3_buckets: All buckets
  • efs_filesystems: All EFS
  • cloudwatch_log_groups: All log groups with retention
  • cloudtrail_trails: All trails
  • secrets: Secrets Manager secrets (with last accessed date)

database

  • rds_instances: All RDS
  • rds_snapshots: Manual snapshots
  • dynamodb_tables: All tables
  • elasticache_clusters: All clusters

networking

  • nat_gateways: All NAT gateways
  • load_balancers: ALBs/NLBs
  • vpc_endpoints: All endpoints
  • public_ipv4_addresses: Public IPv4 inventory from ENIs, EIPs, or Public IP Insights
  • data_transfer_costs: USAGE_TYPE breakdown from Cost Explorer
  • route53_zones: Hosted zones with record counts

serverless

  • lambda_functions: All functions
  • api_gateways: REST/HTTP APIs
  • sqs_queues: All queues
  • step_functions: State machines

reservations

  • reserved_instances: EC2 RIs
  • reserved_db_instances: RDS RIs
  • savings_plans: Active plans
  • ri_purchase_recommendations: AWS-generated RI recommendations
  • sp_purchase_recommendations: AWS-generated SP recommendations

containers

  • ecs_clusters: All ECS clusters
  • ecs_services: Services per cluster
  • ecs_task_definitions: Task definitions
  • eks_clusters: All EKS clusters
  • eks_nodegroups: Node groups per cluster
  • fargate_tasks: Fargate tasks
  • ecr_repositories: ECR repos with lifecycle policy status

advanced_databases

  • aurora_clusters: Aurora DB clusters
  • aurora_instances: Aurora instances
  • documentdb_clusters: DocumentDB clusters
  • neptune_clusters: Neptune clusters
  • redshift_clusters: Redshift clusters

analytics

  • sagemaker_notebooks: Notebook instances
  • sagemaker_endpoints: Inference endpoints
  • emr_clusters: Active EMR clusters
  • opensearch_domains: OpenSearch domains
  • quicksight_datasets: QuickSight datasets

data_pipelines

  • kinesis_streams: Data streams
  • firehose_streams: Firehose delivery streams
  • msk_clusters: MSK Kafka clusters
  • glue_jobs: Glue ETL jobs
  • eventbridge_rules: EventBridge rules

storage_advanced

  • fsx_filesystems: FSx file systems
  • backup_plans: AWS Backup plans
  • backup_vaults: Backup vaults

Cost-Tiered Confidence

Higher-cost findings need MORE evidence before flagging.

Confidence Tiers

TierMonthly CostMin AgeMin ConfidenceSignals Required
LOW< $201 day65%1 signal OK
MEDIUM$20 - $1003 days75%2+ signals
HIGH> $1007 days85%2+ signals

Apply Before Reporting

  1. Calculate monthly_savings → determine tier
  2. Check resource age >= tier.min_age_days
  3. Check confidence >= tier.min_confidence
  4. For MEDIUM/HIGH: verify 2+ signals agree
  5. If any check fails → filter out finding

Quick Adjustments (Apply After Tier Check)

  • -30% if resource < 7 days old
  • -10% for production environment
  • +10% for dev/test environment
  • -30% if part of Auto Scaling Group

Multi-Signal Idle Detection

CRITICAL: Do NOT flag resources as idle based on CPU alone. Use weighted multi-signal scoring.

EC2 Idle Detection

SignalMetricThresholdWeight
CPUCPUUtilization avg< 5%0.40
Network InNetworkIn< 0.1 GB/day0.15
Network OutNetworkOut< 0.1 GB/day0.15
ConnectionsNetworkPacketsIn00.20
Disk I/ODiskReadOps+WriteOps< 10/sec0.10

Idle Score Formula:

idleScore = sum(weights where threshold met)
Threshold: idleScore >= 0.60 required to flag as idle

Required AWS Commands

# Collect ALL signals (not just CPU)
aws cloudwatch get-metric-statistics --namespace AWS/EC2 \
  --metric-name CPUUtilization --dimensions Name=InstanceId,Value={id} \
  --start-time {14d_ago} --end-time {now} --period 86400 --statistics Average Maximum

aws cloudwatch get-metric-statistics --namespace AWS/EC2 \
  --metric-name NetworkIn --dimensions Name=InstanceId,Value={id} \
  --start-time {14d_ago} --end-time {now} --period 86400 --statistics Sum

aws cloudwatch get-metric-statistics --namespace AWS/EC2 \
  --metric-name NetworkPacketsIn --dimensions Name=InstanceId,Value={id} \
  --start-time {14d_ago} --end-time {now} --period 86400 --statistics Sum

Finding Output Format

{
  "check_id": "EC2-001",
  "idle_detection": {
    "signals": {
      "cpu_avg": {"value": 2.1, "threshold": 5, "passed": true, "weight": 0.40},
      "network_in_gb": {"value": 0.05, "threshold": 0.1, "passed": true, "weight": 0.15},
      "connections": {"value": 145, "threshold": 0, "passed": false, "weight": 0.20}
    },
    "idle_score": 0.55,
    "threshold": 0.60,
    "result": "NOT_IDLE - has active connections"
  }
}

AWS Compute Optimizer Integration (FREE)

Use Compute Optimizer as PRIMARY signal for rightsizing and idle detection. Falls back to CloudWatch thresholds if CO is not enabled.

Step 1: Check Enrollment

aws compute-optimizer get-enrollment-status

If status is Active, use CO recommendations. If Inactive, fall back to manual CloudWatch analysis.

Step 2: ML-Powered Rightsizing (EC2-024)

aws compute-optimizer get-ec2-instance-recommendations

Returns recommendations with:

  • finding: UNDER_PROVISIONED, OVER_PROVISIONED, OPTIMIZED, or IDLE
  • recommendationOptions: Specific instance types with projected performance
  • Accounts for CPU, memory, network, and disk (not just CPU)

Use CO finding directly instead of manual threshold checks when available.

Step 3: Idle Detection (EC2-026)

aws compute-optimizer get-idle-recommendations

This dedicated API covers EC2, ASG, EBS, ECS, RDS, and (since Jun 2026) DynamoDB, ElastiCache, MemoryDB, DocumentDB, WorkSpaces, and SageMaker endpoints. It is more accurate than manual idle detection because it uses ML trained on usage patterns.

Fallback (CO Not Enabled)

If Compute Optimizer is not active, use the manual multi-signal idle detection below.


Memory Metric Graceful Degradation (EC2-027)

Check if CloudWatch Agent memory metrics exist. If available, use them to improve idle detection accuracy. If not, proceed without penalizing confidence.

Check Availability

aws cloudwatch list-metrics --namespace CWAgent --metric-name mem_used_percent \
  --dimensions Name=InstanceId,Value={instance_id}

If Available

Add memory as a signal in idle detection:

SignalMetricThresholdWeight
Memorymem_used_percent< 10%0.15

Redistribute weights: CPU 0.35, Network In 0.10, Network Out 0.10, Connections 0.15, Disk I/O 0.10, Memory 0.15

CRITICAL: An instance at <5% CPU but >70% memory is likely a cache server — do NOT flag as idle.

If Not Available

  • Note: "memory_data": "unavailable - CloudWatch Agent not installed"
  • Do NOT reduce confidence due to missing memory data
  • Proceed with standard 5-signal detection

Data Transfer Cost Analysis (NET-016, NET-017)

Most tools miss data transfer costs. Use USAGE_TYPE grouping to surface hidden charges.

Query Data Transfer Breakdown

aws ce get-cost-and-usage \
  --time-period Start={30_days_ago},End={now} \
  --granularity MONTHLY \
  --metrics UnblendedCost \
  --group-by Type=DIMENSION,Key=USAGE_TYPE \
  --filter '{"Dimensions":{"Key":"SERVICE","Values":["Amazon Elastic Compute Cloud - Compute"]}}'

Key Usage Types to Flag

Usage TypeWhat It IsCost
DataTransfer-Regional-BytesCross-AZ traffic$0.01/GB each direction
NatGateway-BytesNAT data processing$0.045/GB
DataTransfer-Out-BytesInternet egress$0.09/GB first 10TB
DataTransfer-In-BytesInternet ingressFree

Findings Format

{
  "check_id": "NET-017",
  "title": "High Data Transfer Costs",
  "monthly_savings": 45.00,
  "details": {
    "cross_az_cost": 23.50,
    "nat_processing_cost": 89.00,
    "internet_egress_cost": 156.00,
    "total_data_transfer_cost": 268.50,
    "recommendation": "VPC endpoints for S3/DynamoDB would eliminate $89/mo in NAT processing"
  }
}

Reservation Purchase Recommendations (RI-007, SP-005)

Query AWS for purchase recommendations instead of just checking coverage gaps.

RI Purchase Recommendation

aws ce get-reservation-purchase-recommendation \
  --service "Amazon Elastic Compute Cloud - Compute" \
  --term-in-years ONE_YEAR \
  --payment-option PARTIAL_UPFRONT \
  --lookback-period-in-days SIXTY_DAYS

Savings Plan Purchase Recommendation

aws ce get-savings-plans-purchase-recommendation \
  --savings-plans-type COMPUTE_SP \
  --term-in-years ONE_YEAR \
  --payment-option PARTIAL_UPFRONT \
  --lookback-period-in-days SIXTY_DAYS

Database Savings Plan Purchase Recommendation (SP-006)

aws ce get-savings-plans-purchase-recommendation \
  --savings-plans-type DATABASE_SP \
  --term-in-years ONE_YEAR \
  --payment-option NO_UPFRONT \
  --lookback-period-in-days SIXTY_DAYS

Database Savings Plans (Dec 2025) cover Aurora, RDS, DynamoDB, ElastiCache (Valkey engine only), DocumentDB, Neptune, and OpenSearch; 1-year no-upfront is the only option.

These return specific amounts and estimated savings. Include in findings as actionable recommendations.


Live Dependency Checks (MANDATORY SAFETY)

Before recommending deletion, verify NO active dependencies.

Dependency Check Matrix

ResourceCheck CommandIf FoundAction
EC2aws autoscaling describe-auto-scaling-instances --instance-ids {id}ASG memberSKIP
NAT Gatewayaws ec2 describe-route-tables --filters "Name=route.nat-gateway-id,Values={id}"Routes existSKIP
ELBaws elbv2 describe-target-health --target-group-arn {arn}Healthy targetsSKIP
EBS Snapshotaws ec2 describe-images --filters "Name=block-device-mapping.snapshot-id,Values={id}"AMI uses itAdd warning
EFSaws efs describe-mount-targets --file-system-id {id}Mount targetsAdd warning

Output When Blocked

{
  "check_id": "EC2-001",
  "resource_id": "i-abc123",
  "dependency_check": {
    "type": "asg_membership",
    "result": "member_of: my-asg",
    "safe_to_recommend": false
  },
  "status": "skipped",
  "skip_reason": "Resource is member of Auto Scaling Group 'my-asg'"
}

DO NOT

  • Recommend deleting EC2 without checking ASG membership
  • Recommend deleting NAT without checking route tables
  • Recommend deleting ELB without checking target health
  • Skip dependency checks to save API calls

ZERO HALLUCINATION PRICING SYSTEM

ABSOLUTE RULE: Never invent, estimate, guess, or approximate a price. Every number must come from a verifiable source.

Pricing Resolution Order (MANDATORY)

For EVERY finding that has a monthly_savings value, you MUST resolve the price using this exact order. Do NOT skip steps.

Step 1: Query AWS Pricing API for the EXACT resource SKU
        ↓ (if API returns a price → USE IT, set pricing_source: "aws_pricing_api")
        ↓ (if API fails or returns empty → go to Step 2)
Step 2: Look up in the Verified Pricing Table below
        ↓ (if found → USE IT, set pricing_source: "verified_table")
        ↓ (if NOT found → go to Step 3)
Step 3: Set monthly_savings: 0, add pricing_unknown: true
        DO NOT GUESS. DO NOT INTERPOLATE. DO NOT "ESTIMATE".

Step 1: AWS Pricing API Queries

ALWAYS try these first. Use --region us-east-1 (Pricing API endpoint).

EC2 Instance Pricing
aws pricing get-products --region us-east-1 \
  --service-code AmazonEC2 \
  --filters \
    "Type=TERM_MATCH,Field=instanceType,Value={ACTUAL_INSTANCE_TYPE}" \
    "Type=TERM_MATCH,Field=location,Value={LOCATION_NAME}" \
    "Type=TERM_MATCH,Field=operatingSystem,Value={OS}" \
    "Type=TERM_MATCH,Field=tenancy,Value=Shared" \
    "Type=TERM_MATCH,Field=preInstalledSw,Value=NA" \
    "Type=TERM_MATCH,Field=capacitystatus,Value=Used" \
  --max-results 1

You MUST set the correct values:

  • {ACTUAL_INSTANCE_TYPE}: The EXACT instance type from describe-instances (e.g., m6i.large, c7g.xlarge)
  • {OS}: Check the Platform field from describe-instances. If windows → Windows, if absent → Linux
  • {LOCATION_NAME}: Map from the region being scanned (see Region Map below)
RDS Instance Pricing
aws pricing get-products --region us-east-1 \
  --service-code AmazonRDS \
  --filters \
    "Type=TERM_MATCH,Field=instanceType,Value={ACTUAL_DB_INSTANCE_TYPE}" \
    "Type=TERM_MATCH,Field=location,Value={LOCATION_NAME}" \
    "Type=TERM_MATCH,Field=databaseEngine,Value={ACTUAL_ENGINE}" \
    "Type=TERM_MATCH,Field=deploymentOption,Value={ACTUAL_DEPLOYMENT}" \
  --max-results 1

You MUST set the correct values:

  • {ACTUAL_ENGINE}: From describe-db-instances → Engine field. Map: postgres → PostgreSQL, mysql → MySQL, mariadb → MariaDB, aurora-postgresql → Aurora PostgreSQL, aurora-mysql → Aurora MySQL
  • {ACTUAL_DEPLOYMENT}: From describe-db-instances → MultiAZ field. If true → Multi-AZ, if false → Single-AZ
EBS Volume Pricing
aws pricing get-products --region us-east-1 \
  --service-code AmazonEC2 \
  --filters \
    "Type=TERM_MATCH,Field=volumeApiName,Value={ACTUAL_VOLUME_TYPE}" \
    "Type=TERM_MATCH,Field=location,Value={LOCATION_NAME}" \
  --max-results 5
Other Services (ElastiCache, OpenSearch, DocumentDB, Neptune, Redshift, SageMaker, MSK, FSx)

Read ${CLAUDE_PLUGIN_ROOT}/references/pricing-api-queries.md for the query template of any other service (and the complete region location map). Same pattern: --service-code for the service, instanceType + location TERM_MATCH filters, --max-results 1.

Parsing the Pricing API Response

The response contains nested JSON. Extract the On-Demand hourly price:

PriceList[0] → parse as JSON → terms.OnDemand → first value → priceDimensions → first value → pricePerUnit.USD

monthly_cost = hourly_price × 730

If the response is empty (PriceList: []), the API did not find a match. Go to Step 2.

Region Location Map

Common regions:

Region CodeLocation Name
us-east-1US East (N. Virginia)
us-east-2US East (Ohio)
us-west-2US West (Oregon)
eu-west-1EU (Ireland)
eu-central-1EU (Frankfurt)
ap-south-1Asia Pacific (Mumbai)
ap-southeast-1Asia Pacific (Singapore)
ap-northeast-1Asia Pacific (Tokyo)

For any other region, read the complete 29-region map in ${CLAUDE_PLUGIN_ROOT}/references/pricing-api-queries.md. If the region is not in that map either, do NOT guess the location name. Set pricing_unknown: true.

Step 2: Verified Pricing Table (Fallback ONLY)

Use this table ONLY if the Pricing API returned no results. These are us-east-1 On-Demand prices.

If the resource is NOT in us-east-1 and the API failed, set pricing_unknown: true. Do NOT use this table for other regions.

EC2 Instances (Linux, us-east-1)
Instance TypeHourlyMonthly (×730)
t2.nano$0.0058$4.23
t2.micro$0.0116$8.47
t3.nano$0.0052$3.80
t3.micro$0.0104$7.59
t3.small$0.0208$15.18
t3.medium$0.0416$30.37
t3.large$0.0832$60.74
m5.large$0.096$70.08
m5.xlarge$0.192$140.16
r5.large$0.126$91.98
r5.xlarge$0.252$183.96
RDS Instances (PostgreSQL, Single-AZ, us-east-1)
Instance TypeHourlyMonthly
db.t3.micro$0.017$12.41
db.t3.small$0.034$24.82
db.t3.medium$0.068$49.64
db.r5.large$0.25$182.50
db.r5.xlarge$0.50$365.00
db.r5.2xlarge$1.00$730.00
Fixed-Price Resources (all regions)
ResourceMonthlySource
Public IPv4 address$3.65$0.005/hr × 730 hours
EIP (unattached)$3.65Same public IPv4 hourly charge
EKS Cluster (standard support)$73.00$0.10/hr × 730 = $73.00
EKS Cluster (extended support)$438.00$0.60/hr × 730 = $438.00
RDS Extended Support (year 1-2)$73.00 per vCPU$0.100/vCPU-hr × 730 (us-east-1)
RDS Extended Support (year 3+)$146.00 per vCPU$0.200/vCPU-hr × 730 (us-east-1)
ElastiCache Redis 4/5 extended support+80% of node priceSurcharge since Feb 2026; +160% from Feb 2028
Per-Unit Storage (us-east-1)
TypePriceUnit
EBS gp3$0.08GB-month
EBS gp2$0.10GB-month
EBS io2$0.125GB-month (storage; ADD tiered IOPS cost per Rule 10)
EBS snapshot$0.05GB-month
S3 Standard$0.023GB-month (first 50TB)
S3 IA$0.0125GB-month
EFS$0.30GB-month
CW Logs Storage$0.03GB-month
CW Logs Ingestion$0.50GB first 10TB/mo, tiered down to $0.05 at scale (NOT recurring, NOT saveable by retention)
DynamoDB on-demand writes$0.625per million WRU (halved Nov 2024 — do not use pre-2025 prices)
DynamoDB on-demand reads$0.125per million RRU (halved Nov 2024)
Per-Unit Compute (us-east-1)
TypePriceUnit
Fargate vCPU$0.04048per vCPU-hour
Fargate GB$0.004445per GB-hour
Lambda x86$0.0000166667per GB-second
Lambda ARM$0.0000133334per GB-second
Lambda requests$0.20per 1M requests
Kinesis shard$0.015per shard-hour

Step 3: When Price Is Unknown

If the instance type, DB engine, node type, or resource SKU is NOT found in Step 1 (API) AND NOT found in Step 2 (table), you MUST:

{
  "check_id": "EC2-001",
  "resource_id": "i-abc123",
  "monthly_savings": 0,
  "confidence": 50,
  "details": {
    "pricing_unknown": true,
    "pricing_resolution_attempted": [
      "aws_pricing_api: no results for c6gd.2xlarge in EU (Frankfurt)",
      "verified_table: c6gd.2xlarge not listed"
    ],
    "instance_type": "c6gd.2xlarge",
    "recommendation": "Resource appears idle but savings cannot be calculated - price lookup required"
  }
}

NEVER do any of these:

  • "A c6gd.2xlarge is similar to a c5.2xlarge, so I'll use that price" → NO
  • "Based on the family pattern, this probably costs about $X" → NO
  • "I'll estimate conservatively at $Y" → NO
  • "A 2xlarge is roughly 2× an xlarge" → NO

ANTI-HALLUCINATION RULES (MANDATORY)

These rules are NON-NEGOTIABLE. Violating any of them produces invalid findings.

Rule 1: Every Number Must Have a Source

Every monthly_savings value MUST trace back to one of:

  • AWS Pricing API response (best)
  • Verified Pricing Table above (acceptable for us-east-1)
  • AWS Cost Explorer response (for reservation/SP recommendations)
  • $0 with pricing_unknown: true (when price cannot be determined)

There is NO fifth option. You cannot derive, interpolate, or estimate a price from any other source.

Rule 2: Never Treat Missing Data as Zero

When a CloudWatch metric returns empty Datapoints: []:

  • DO NOT assume the value is 0
  • DO NOT treat it as "no activity"
  • DO skip that signal in idle score calculation
  • DO reduce the denominator (available signals) accordingly
  • DO note in details: "signal_name": {"value": null, "status": "no_data", "action": "skipped"}

If fewer than 2 signals have data, do NOT generate an idle finding. Set:

{
  "status": "insufficient_data",
  "skip_reason": "Only 1 of 5 signals returned data - cannot determine idle status"
}

Rule 3: Never Pick a Creative Downsize Target

For over-provisioned findings, you may ONLY recommend:

  1. The EXACT target from AWS Compute Optimizer (if enrolled and recommendation exists)
  2. One size down in the SAME instance family (e.g., m5.xlarge → m5.large, NEVER m5.xlarge → t3.large)
  3. Nothing — if neither option is available, flag as over-provisioned but set monthly_savings: 0 with "savings_note": "Manual rightsizing analysis required - no automated target available"

NEVER do:

  • Jump across instance families (m5 → t3, r5 → m5)
  • Skip multiple sizes (xlarge → small)
  • Suggest a completely different instance type based on "workload analysis"

Rule 4: Use Fixed Conservative Rates for Migration Savings

These migration types have variable real-world savings. Use ONLY these fixed rates:

Migration TypeFixed RateDo NOT Use
Graviton (x86 → ARM)20%"up to 40%"
Spot instances50%"up to 90%"
ARM Lambda20%"34% better price-performance"
Previous gen upgrade10%"up to 40% better price-performance"
GP2 → GP320%varies by size
S3 Standard → IA40% storage only"save on everything"
RI 1yr Partial Upfront35%"up to 72%"
SP 1yr No Upfront25%"up to 66%"
Database SP 1yr No Upfront20%"up to 35%"
ElastiCache Redis → Valkey20% node cost"up to 33%" (that is serverless only)

Generation guard: never recommend a target SKU you have not confirmed exists (Rule 18). ElastiCache tops out at m7g/r7g — cache.m8g/cache.r8g do NOT exist. The latest burstable EC2 family is still t4g — there is no t5g.

ALWAYS note: "savings_type": "estimated_migration", "fixed_rate_used": "20%_graviton"

Rule 5: Never Estimate Data Transfer Composition

For NAT Gateway, Cross-AZ, and data transfer findings:

  • Report the total cost from Cost Explorer (this is a FACT, not an estimate)
  • DO NOT estimate what percentage of traffic is S3, DynamoDB, or other services
  • DO NOT claim "VPC endpoints would save $X" unless you can verify the specific traffic type
  • DO flag as "needs_manual_review": true with recommendation to analyze traffic logs
{
  "check_id": "NET-016",
  "monthly_savings": 0,
  "details": {
    "nat_total_cost": 89.00,
    "nat_total_cost_source": "aws_cost_explorer",
    "needs_manual_review": true,
    "recommendation": "NAT Gateway costs $89/mo. Analyze VPC Flow Logs to identify which traffic could use VPC Gateway Endpoints (free for S3/DynamoDB). Cannot estimate savings without traffic breakdown."
  }
}

Rule 6: Every Finding Must Include Machine-Verifiable Calculation

{
  "monthly_savings": 70.08,
  "details": {
    "calculation": "0.096 × 730 = 70.08",
    "calculation_inputs": {
      "hourly_rate": 0.096,
      "hours_per_month": 730
    },
    "pricing_source": "aws_pricing_api",
    "pricing_api_query": "instanceType=m5.large, location=US East (N. Virginia), OS=Linux"
  }
}

Every calculation MUST have:

  • calculation: Human-readable formula with actual numbers
  • calculation_inputs: Machine-parseable input values
  • pricing_source: One of aws_pricing_api, verified_table, aws_cost_explorer, pricing_unknown
  • pricing_api_query: The filters used (if source is aws_pricing_api)

Rule 7: Never Generate a Finding Without Raw API Evidence

Every finding MUST reference data from an actual AWS API response:

  • resource_id MUST come from an AWS API response (describe-instances, describe-volumes, etc.)
  • instance_type MUST come from the API response, NOT from your memory or assumptions
  • Metric values MUST come from CloudWatch API responses
  • Cost data MUST come from Cost Explorer API responses

If you cannot trace a value back to a specific API call you made in this session, do NOT include it.

Rule 8: Sanity Check - Savings Cannot Exceed Service Spend

BEFORE reporting ANY finding, verify:

finding.monthly_savings <= service_monthly_spend

Query the actual service spend:

aws ce get-cost-and-usage \
  --time-period Start={first_of_last_month},End={first_of_this_month} \
  --granularity MONTHLY \
  --metrics UnblendedCost \
  --filter '{"Dimensions":{"Key":"SERVICE","Values":["{SERVICE_NAME}"]}}'

Service name mappings:

DomainCost Explorer Service Name
EC2 instancesAmazon Elastic Compute Cloud - Compute
EBS volumesAmazon Elastic Compute Cloud - Compute
RDSAmazon Relational Database Service
ElastiCacheAmazon ElastiCache
LambdaAWS Lambda
S3Amazon Simple Storage Service
CloudWatchAmazonCloudWatch
NAT GatewayAmazon Elastic Compute Cloud - Compute
OpenSearchAmazon OpenSearch Service
RedshiftAmazon Redshift
DynamoDBAmazon DynamoDB
EFSAmazon Elastic File System
SageMakerAmazon SageMaker
EKSAmazon Elastic Container Service for Kubernetes
KinesisAmazon Kinesis
MSKAmazon Managed Streaming for Apache Kafka
GlueAWS Glue
DocumentDBAmazon DocumentDB (with MongoDB compatibility)
NeptuneAmazon Neptune
FSxAmazon FSx

If the finding's monthly_savings exceeds the service's actual monthly spend:

  1. Count resources in that service from your resource inventory
  2. If 1-2 resources in service → savings CAN be up to 100% of service spend (a single idle RDS instance IS the entire RDS spend)
  3. If 3+ resources in service → cap at 90% and add "requires_validation": true
  4. If savings > 110% of service spend → the finding is WRONG, recalculate using correct formula

NEVER blindly cap at a fixed percentage — verify resource count first.

Rule 9: Distinguish Storage vs Ingestion (CloudWatch Logs)

CloudWatch Logs has TWO completely separate cost components:

  • Ingestion: $0.50/GB — charged ONCE when logs arrive. NOT affected by retention policy.
  • Storage: $0.03/GB-month — charged MONTHLY for stored data. Reduced by shorter retention.

Setting retention to 30 days ONLY reduces storage costs. The formula is:

savings = stored_gb × $0.03

NEVER use $0.50 in a retention-related savings calculation.

Rule 10: EBS Pricing Must Include ALL Components

EBS pricing has up to 3 components. You MUST account for all of them:

Componentgp2gp3io2
Storage$0.10/GB$0.08/GB$0.125/GB
IOPSIncluded (burst)Free up to 3000, then $0.005/IOPSTiered: $0.065 (first 32K), $0.046 (32K-64K), $0.032 (>64K) per IOPS
ThroughputIncludedFree up to 125 MB/s, then $0.04/MBpsIncluded

Note: gp3 now scales to 64 TiB / 80,000 IOPS / 2,000 MiB/s (Sep 2025), so most io1/io2 volumes are eligible for a gp3 migration finding.

For unattached EBS findings, calculate ALL components:

gp3_cost = (size_gb × 0.08) + (max(0, iops - 3000) × 0.005) + (max(0, throughput - 125) × 0.04)

Get IOPS and throughput from the describe-volumes response (Iops and Throughput fields).

Rule 11: RDS Pricing Must Use Correct Deployment Option

  • Check the MultiAZ field from describe-db-instances
  • If MultiAZ: true, query Pricing API with deploymentOption=Multi-AZ (cost is ~2× Single-AZ)
  • NEVER use Single-AZ pricing for a Multi-AZ instance

Rule 12: OS-Specific EC2 Pricing

  • Check the Platform field from describe-instances
  • If Platform: windows → query with operatingSystem=Windows (typically 2× Linux price)
  • If Platform is absent → query with operatingSystem=Linux
  • NEVER use Linux pricing for Windows instances

Rule 13: Minimum Savings Floor

Do NOT report findings with monthly_savings < $1.00 (unless monthly_savings is exactly $0 with pricing_unknown: true). These create noise without actionable value.

Rule 14: Flag Findings > $100 for Review

Any finding with monthly_savings > $100 MUST include:

{
  "requires_validation": true,
  "validation_reason": "Savings exceed $100 threshold"
}

Rule 15: Check RI/SP Coverage Before Calculating Savings

Resources covered by Reserved Instances or Savings Plans cost LESS than On-Demand. Terminating an RI-covered instance doesn't save the On-Demand price — the RI payment continues.

Step 1: Check InstanceLifecycle from describe-instances:

  • If absent → On-Demand
  • If spot → Spot instance (see Rule 16)

Step 2: For On-Demand instances, check if RI/SP coverage exists for this instance type:

aws ce get-reservation-coverage \
  --time-period Start={first_of_last_month},End={first_of_this_month} \
  --granularity MONTHLY \
  --filter '{"Dimensions":{"Key":"INSTANCE_TYPE","Values":["{instance_type}"]}}'

Step 3: If CoverageHoursPercentage > 80%:

  • Add "covered_by_ri_or_sp": true to finding details
  • Add "savings_assumption": "on_demand_pricing_used_but_ri_sp_covers_this_type"
  • Reduce confidence by -20%

Rule 16: Check for Spot Instances

From describe-instances, check InstanceLifecycle:

  • If "spot" → actual cost is 50-90% lower than On-Demand
  • Use On-Demand_price × 0.3 as conservative Spot cost estimate
  • Add "instance_lifecycle": "spot" to details

Rule 17: Handle Burstable Instances (t2/t3/t4g)

For instance types starting with t2., t3., t3a., t4g.:

Check CPU Credit Balance trend:

aws cloudwatch get-metric-statistics --namespace AWS/EC2 \
  --metric-name CPUCreditBalance --dimensions Name=InstanceId,Value={id} \
  --start-time {14d_ago} --end-time {now} --period 86400 --statistics Average
  • Credits increasing over 14 days → confirms idle (credits accumulating)
  • Credits decreasing or stable → may burst periodically, reduce confidence by -15%
  • Credit data unavailable → reduce confidence by -10% for burstable instances

Rule 18: Downsize Floor Check

Before recommending a downsize, verify the target size EXISTS:

  • Size order: nano → micro → small → medium → large → xlarge → 2xlarge → ...
  • If already at smallest size in family (e.g., t3.nano, c7g.large), set monthly_savings: 0 with "downsize_not_possible": "already_at_minimum_size"
  • If unsure whether target exists, query the Pricing API — empty result = size doesn't exist

Rule 19: Detect IaC-Managed Resources

Check resource tags for infrastructure-as-code management:

Tag KeyMeaning
aws:cloudformation:stack-nameCloudFormation managed
Tags containing terraformTerraform managed
Tags containing pulumiPulumi managed

If IaC tags found:

  • Add "managed_by_iac": true to details
  • Change recommendation to "Review with IaC team — direct deletion will trigger recreation"
  • Reduce confidence by -10%

Rule 20: Pricing API Error Handling

If aws pricing get-products returns an ERROR (not empty results):

  • Throttling (ThrottlingException): Wait 2 seconds, retry ONCE. If still fails → go to Step 2 (table)
  • Access denied: Skip to Step 2 immediately
  • Any other error: Skip to Step 2 immediately
  • Add "pricing_api_status": "error_type" to details

Rule 21: Cost Explorer Availability

Before generating ANY findings, verify Cost Explorer returns data:

aws ce get-cost-and-usage \
  --time-period Start={yesterday},End={today} \
  --granularity DAILY \
  --metrics UnblendedCost

If empty or DataUnavailableException:

  • Set "cost_explorer_available": false in metadata
  • Skip Rule 8 (sanity check against service spend)
  • Reduce ALL confidence scores by -15%
  • Add to every finding: "billing_validation_skipped": "cost_explorer_unavailable"

Common Pricing Mistakes

#MistakeCorrect Approach
1CW Logs: stored_gb × $0.50stored_gb × $0.03 (storage, not ingestion)
2Savings > service spendVerify resource count first, cap only if 3+ resources
3Missing instance type → guessmonthly_savings=0, pricing_unknown=true
4Missing metric → assume idleSkip that signal, note as no_data
5Creative downsize (m5→t3)Same family, one size down only
6NAT traffic composition guessneeds_manual_review=true
7Windows priced as LinuxQuery API with operatingSystem=Windows
8Single-AZ price for Multi-AZQuery API with deploymentOption=Multi-AZ
9EBS storage onlyInclude IOPS + throughput costs
10"Up to X%" percentagesUse fixed conservative rates
11Interpolating sizesQuery Pricing API for exact type
12us-east-1 table for other regionsUse Pricing API for non-us-east-1
13On-Demand price for Spot/RICheck InstanceLifecycle and RI coverage
14Delete IaC-managed resourceFlag for IaC team review

Rules

  1. Only return confidence >= 50
  2. Include Name tags in resource_name
  3. Return [] if no issues
  4. Price resolution: API first → verified table → $0 with pricing_unknown
  5. Every finding needs calculation + pricing_source in details
  6. Sanity-check savings vs service billing (context-aware, not fixed cap)
  7. Flag findings > $100 for validation
  8. Missing CloudWatch data = skip signal, not zero
  9. Downsize: same family, one size down, verify target exists
  10. Data transfer composition: flag for manual review, not estimate
  11. Correct OS, deployment option, all EBS components
  12. No findings with monthly_savings between $0.01 and $0.99
  13. Check RI/SP coverage and Spot lifecycle before pricing
  14. Detect burstable instance credit patterns
  15. Flag IaC-managed resources for team review
  16. Handle Pricing API errors gracefully (retry then fallback)
  17. Verify Cost Explorer availability before sanity checks

Hooks 1

MCP servers 1

Sponsors

Details

Marketplace
prajapatimehul/claude-aws-cost-saver
Source
plugins/aws-cost-saver
Author
Mehul Prajapati
Category
Infrastructure
Keywords
aws, cost, optimization, cloud, finops, savings