
aws-cost-saver
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-marketplaceRun it inside Claude Code after adding the marketplace with /plugin marketplace add prajapatimehul/claude-aws-cost-saver.
Contents
Discovered from sourceSkills 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):
| Score | Meaning |
|---|---|
| 90-100 | Definite savings - act immediately |
| 70-89 | High confidence - safe to implement |
| 50-69 | Medium confidence - needs validation |
| 25-49 | Low confidence - likely false positive |
| 0-24 | Skip - 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
- Read
findings.json - Launch 4 parallel review agents (use Task tool)
- Collect agent results
- Calculate final confidence (average of 4 agents)
- Apply filter threshold (50)
- Update findings with review status
- Generate summary report
- 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):
- Queries real AWS Pricing API for EC2, RDS, EBS
- Updates
monthly_savingswith validated value - Marks
api_validated: truein metadata
For findings below threshold:
- Preserves pricing that already carries a compliant
pricing_sourceandcalculation - Resolves from the verified us-east-1 table where an exact formula exists
- Otherwise sets
monthly_savings=0withpricing_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):
| Resource | Price | Unit | Monthly (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
- Load
findings.json - For each finding:
- Identify resource type from
check_idanddetails - Query AWS Pricing API (or use cached known prices)
- Calculate correct savings based on finding category
- Update
monthly_savingsfield - Add
pricing_validatedmetadata
- Identify resource type from
- Recalculate
total_monthly_savingsin metadata - 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:
| Service | Components | What Retention Affects |
|---|---|---|
| CloudWatch Logs | Ingestion ($0.50/GB) + Storage ($0.03/GB) | Storage ONLY |
| S3 | Storage + Requests + Transfer | Storage + old versions |
| EBS | Storage + IOPS + Throughput | Storage ONLY |
| RDS | Compute + Storage + I/O | Depends 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:
| Agent | Domain | Checks |
|---|---|---|
| 1 | compute | EC2, EBS, AMIs, snapshots, EIPs, Compute Optimizer |
| 2 | storage | S3, EFS, CloudWatch Logs, CloudTrail, Secrets Manager |
| 3 | database | RDS, DynamoDB, ElastiCache |
| 4 | networking | NAT, ELB, VPC endpoints, public IPv4, data transfer, Route 53 |
| 5 | serverless | Lambda, API Gateway, SQS, Step Functions |
| 6 | reservations | RI coverage, Savings Plans, purchase recommendations |
| 7 | containers | ECS, EKS, Fargate, ECR |
| 8 | advanced_databases | Aurora, DocumentDB, Neptune, Redshift |
| 9 | analytics | SageMaker, EMR, OpenSearch, QuickSight |
| 10 | data_pipelines | Kinesis, MSK, Glue, EventBridge |
| 11 | storage_advanced | FSx, AWS Backup |
Pass to each:
region: Active region(s)compliance: User's selectionprofile: AWS profile namecompute_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 APIverified_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:
- Resource Age: -30% confidence if created < 7 days ago
- Environment: -10% for production, +10% for dev/test (from Name tags)
Mark findings:
approvedif confidence ≥ 70%needs_validationif confidence 50-69%filteredif 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 Type | Correct Formula |
|---|---|
| CW Logs Retention | stored_gb × $0.03 (storage only) |
| Unattached EBS | size_gb × price_per_gb |
| Idle EC2 | hourly_rate × 730 |
| Over-provisioned | current_cost - recommended_cost |
| No RI Coverage | on_demand_cost × savings_percent |
| Public IPv4 Charges | address_count × $0.005 × 730 |
| Idle EKS Cluster | (cluster_hourly_rate × 730) + node_costs |
| Idle Fargate Task | vCPU_hrs × $0.04048 + GB_hrs × $0.004445 |
| Idle Aurora | hourly_rate × 730 + storage_gb × $0.10 |
| Idle Redshift | node_hourly × nodes × 730 |
| Idle SageMaker Endpoint | hourly_rate × 730 |
| Over-provisioned Kinesis | shards × $0.015/hr × 730 |
| Idle MSK Cluster | broker_cost × brokers |
| NAT Data Processing | gb_processed × $0.045 |
| Cross-AZ Transfer | gb_transferred × $0.02 (both directions) |
| Unused Secrets | count × $0.40 |
| Unused Route 53 Zone | count × $0.50 |
| EBS Snapshot Archive | gb_months × ($0.05 - $0.0125) |
| RI Purchase Savings | From ce get-reservation-purchase-recommendation |
| SP Purchase Savings | From ce get-savings-plans-purchase-recommendation |
6.5.4: Flag & Correct Invalid Findings
If a finding fails validation:
- Recalculate using correct formula
- Update
monthly_savingswith corrected value - Add
pricing_corrected: trueto details - 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
| Component | Calculation | Range |
|---|---|---|
| Impact | min(monthly_savings / 100, 10) | 0.1 - 10 |
| Confidence | confidence / 100 | 0.5 - 1.0 |
| Urgency | Based on idle duration | 0.7 - 1.5 |
| Risk Multiplier | Based on environment | 0.5 - 1.5 |
Urgency Values
| Idle Duration | Urgency |
|---|---|
| > 30 days | 1.5 |
| 14-30 days | 1.2 |
| 7-14 days | 1.0 |
| < 7 days | 0.7 |
Risk Multiplier Values
| Environment | Multiplier |
|---|---|
| dev/test | 1.5 (lower risk) |
| staging | 1.0 |
| production | 0.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
| Score | Priority | Action |
|---|---|---|
| > 5.0 | Critical | This week |
| 2.0-5.0 | High | This month |
| 1.0-2.0 | Medium | Next quarter |
| < 1.0 | Low | When 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:
- Total approved savings
- Top 5 findings
- 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_advancedregion: AWS region to scancompliance: [HIPAA, SOC2, PCI-DSS] or emptyprofile: AWS profile namespend_hotspots: Optional Cost Explorer service and usage-type hotspots from the account-wide pre-scancost_optimization_hub_recommendations: Optional accelerator input if Cost Optimization Hub is enabled
11 Domains (180 checks total)
| Domain | Checks | Resources |
|---|---|---|
| compute | 28 | EC2, EBS, AMIs, snapshots, EIPs, Compute Optimizer, Cost Optimization Hub |
| storage | 24 | S3, EFS, CloudWatch Logs, CloudTrail, Secrets Manager |
| database | 17 | RDS (incl. extended support), DynamoDB, ElastiCache (incl. Valkey migration) |
| networking | 19 | NAT, ELB, VPC endpoints, public IPv4, data transfer, Route 53 |
| serverless | 11 | Lambda, API Gateway, SQS, Step Functions |
| reservations | 13 | RI coverage, Savings Plans (incl. Database SP), purchase recommendations |
| containers | 17 | ECS, EKS (incl. extended support versions), Fargate, ECR |
| advanced_databases | 18 | Aurora, DocumentDB, Neptune, Redshift |
| analytics | 15 | SageMaker, EMR, OpenSearch, QuickSight |
| data_pipelines | 12 | Kinesis, MSK, Glue, EventBridge |
| storage_advanced | 6 | FSx, AWS Backup |
Workflow
- 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. - Start from Cost Explorer spend hotspots and prioritize the highest-cost services or usage types first
- Run AWS CLI commands via MCP tool
- Save resource inventory
- Compare against thresholds
- Return findings + resources
Spend-Led Scan Order
Do not scan purely from inventory. Use account-level spend context first:
- Read the top services from Cost Explorer
- For high-cost services, inspect top
USAGE_TYPErows before applying heuristics - Prioritize checks that match the bill shape:
PublicIPv4*->NET-018,NET-001NatGateway*->NET-016,NET-007,NET-002DataTransfer-Regional-Bytes->NET-004,NET-017DataTransfer-Out-Bytes->NET-005,NET-006,NET-008Snapshot*->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
estimatedMonthlySavingsas the authoritative number for resources it covers (rightsizing, idle, GP2→GP3, Graviton, RI/SP purchases) — its estimates already account for existing RI/SP discounts. Setpricing_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
| Compliance | Rule | skip_reason |
|---|---|---|
| HIPAA | Skip phi=true tags, healthcare names | hipaa-protected |
| SOC2 | Don't delete logs (but CAN set retention) | soc2-audit-required |
| PCI-DSS | Skip pci=true tags, payment VPCs | pci-dss-protected |
Tag-Based Exclusions
SkipCostOpt Tag
Resources with SkipCostOpt=true are excluded from ALL checks.
Exclusion Tags (Honor Any)
| Tag Key | Truthy Values |
|---|---|
| SkipCostOpt | true, 1, yes |
| CostOptExclude | true, 1, yes |
| DoNotOptimize | true, 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 instancesebs_volumes: All volumeselastic_ips: All EIPssnapshots: Account snapshotsamis: Account AMIscompute_optimizer_status: Enrollment status (Active/Inactive)compute_optimizer_recommendations: CO recommendations (if enrolled)
storage
s3_buckets: All bucketsefs_filesystems: All EFScloudwatch_log_groups: All log groups with retentioncloudtrail_trails: All trailssecrets: Secrets Manager secrets (with last accessed date)
database
rds_instances: All RDSrds_snapshots: Manual snapshotsdynamodb_tables: All tableselasticache_clusters: All clusters
networking
nat_gateways: All NAT gatewaysload_balancers: ALBs/NLBsvpc_endpoints: All endpointspublic_ipv4_addresses: Public IPv4 inventory from ENIs, EIPs, or Public IP Insightsdata_transfer_costs: USAGE_TYPE breakdown from Cost Explorerroute53_zones: Hosted zones with record counts
serverless
lambda_functions: All functionsapi_gateways: REST/HTTP APIssqs_queues: All queuesstep_functions: State machines
reservations
reserved_instances: EC2 RIsreserved_db_instances: RDS RIssavings_plans: Active plansri_purchase_recommendations: AWS-generated RI recommendationssp_purchase_recommendations: AWS-generated SP recommendations
containers
ecs_clusters: All ECS clustersecs_services: Services per clusterecs_task_definitions: Task definitionseks_clusters: All EKS clusterseks_nodegroups: Node groups per clusterfargate_tasks: Fargate tasksecr_repositories: ECR repos with lifecycle policy status
advanced_databases
aurora_clusters: Aurora DB clustersaurora_instances: Aurora instancesdocumentdb_clusters: DocumentDB clustersneptune_clusters: Neptune clustersredshift_clusters: Redshift clusters
analytics
sagemaker_notebooks: Notebook instancessagemaker_endpoints: Inference endpointsemr_clusters: Active EMR clustersopensearch_domains: OpenSearch domainsquicksight_datasets: QuickSight datasets
data_pipelines
kinesis_streams: Data streamsfirehose_streams: Firehose delivery streamsmsk_clusters: MSK Kafka clustersglue_jobs: Glue ETL jobseventbridge_rules: EventBridge rules
storage_advanced
fsx_filesystems: FSx file systemsbackup_plans: AWS Backup plansbackup_vaults: Backup vaults
Cost-Tiered Confidence
Higher-cost findings need MORE evidence before flagging.
Confidence Tiers
| Tier | Monthly Cost | Min Age | Min Confidence | Signals Required |
|---|---|---|---|---|
| LOW | < $20 | 1 day | 65% | 1 signal OK |
| MEDIUM | $20 - $100 | 3 days | 75% | 2+ signals |
| HIGH | > $100 | 7 days | 85% | 2+ signals |
Apply Before Reporting
- Calculate monthly_savings → determine tier
- Check resource age >= tier.min_age_days
- Check confidence >= tier.min_confidence
- For MEDIUM/HIGH: verify 2+ signals agree
- 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
| Signal | Metric | Threshold | Weight |
|---|---|---|---|
| CPU | CPUUtilization avg | < 5% | 0.40 |
| Network In | NetworkIn | < 0.1 GB/day | 0.15 |
| Network Out | NetworkOut | < 0.1 GB/day | 0.15 |
| Connections | NetworkPacketsIn | 0 | 0.20 |
| Disk I/O | DiskReadOps+WriteOps | < 10/sec | 0.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 IDLErecommendationOptions: 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:
| Signal | Metric | Threshold | Weight |
|---|---|---|---|
| Memory | mem_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 Type | What It Is | Cost |
|---|---|---|
DataTransfer-Regional-Bytes | Cross-AZ traffic | $0.01/GB each direction |
NatGateway-Bytes | NAT data processing | $0.045/GB |
DataTransfer-Out-Bytes | Internet egress | $0.09/GB first 10TB |
DataTransfer-In-Bytes | Internet ingress | Free |
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
| Resource | Check Command | If Found | Action |
|---|---|---|---|
| EC2 | aws autoscaling describe-auto-scaling-instances --instance-ids {id} | ASG member | SKIP |
| NAT Gateway | aws ec2 describe-route-tables --filters "Name=route.nat-gateway-id,Values={id}" | Routes exist | SKIP |
| ELB | aws elbv2 describe-target-health --target-group-arn {arn} | Healthy targets | SKIP |
| EBS Snapshot | aws ec2 describe-images --filters "Name=block-device-mapping.snapshot-id,Values={id}" | AMI uses it | Add warning |
| EFS | aws efs describe-mount-targets --file-system-id {id} | Mount targets | Add 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 fromdescribe-instances(e.g., m6i.large, c7g.xlarge){OS}: Check thePlatformfield from describe-instances. Ifwindows→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}: Fromdescribe-db-instances→Enginefield. Map:postgres→PostgreSQL,mysql→MySQL,mariadb→MariaDB,aurora-postgresql→Aurora PostgreSQL,aurora-mysql→Aurora MySQL{ACTUAL_DEPLOYMENT}: Fromdescribe-db-instances→MultiAZfield. Iftrue→Multi-AZ, iffalse→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 Code | Location Name |
|---|---|
| us-east-1 | US East (N. Virginia) |
| us-east-2 | US East (Ohio) |
| us-west-2 | US West (Oregon) |
| eu-west-1 | EU (Ireland) |
| eu-central-1 | EU (Frankfurt) |
| ap-south-1 | Asia Pacific (Mumbai) |
| ap-southeast-1 | Asia Pacific (Singapore) |
| ap-northeast-1 | Asia 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 Type | Hourly | Monthly (×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 Type | Hourly | Monthly |
|---|---|---|
| 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)
| Resource | Monthly | Source |
|---|---|---|
| Public IPv4 address | $3.65 | $0.005/hr × 730 hours |
| EIP (unattached) | $3.65 | Same 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 price | Surcharge since Feb 2026; +160% from Feb 2028 |
Per-Unit Storage (us-east-1)
| Type | Price | Unit |
|---|---|---|
| EBS gp3 | $0.08 | GB-month |
| EBS gp2 | $0.10 | GB-month |
| EBS io2 | $0.125 | GB-month (storage; ADD tiered IOPS cost per Rule 10) |
| EBS snapshot | $0.05 | GB-month |
| S3 Standard | $0.023 | GB-month (first 50TB) |
| S3 IA | $0.0125 | GB-month |
| EFS | $0.30 | GB-month |
| CW Logs Storage | $0.03 | GB-month |
| CW Logs Ingestion | $0.50 | GB first 10TB/mo, tiered down to $0.05 at scale (NOT recurring, NOT saveable by retention) |
| DynamoDB on-demand writes | $0.625 | per million WRU (halved Nov 2024 — do not use pre-2025 prices) |
| DynamoDB on-demand reads | $0.125 | per million RRU (halved Nov 2024) |
Per-Unit Compute (us-east-1)
| Type | Price | Unit |
|---|---|---|
| Fargate vCPU | $0.04048 | per vCPU-hour |
| Fargate GB | $0.004445 | per GB-hour |
| Lambda x86 | $0.0000166667 | per GB-second |
| Lambda ARM | $0.0000133334 | per GB-second |
| Lambda requests | $0.20 | per 1M requests |
| Kinesis shard | $0.015 | per 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:
- The EXACT target from AWS Compute Optimizer (if enrolled and recommendation exists)
- One size down in the SAME instance family (e.g., m5.xlarge → m5.large, NEVER m5.xlarge → t3.large)
- Nothing — if neither option is available, flag as over-provisioned but set
monthly_savings: 0with"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 Type | Fixed Rate | Do NOT Use |
|---|---|---|
| Graviton (x86 → ARM) | 20% | "up to 40%" |
| Spot instances | 50% | "up to 90%" |
| ARM Lambda | 20% | "34% better price-performance" |
| Previous gen upgrade | 10% | "up to 40% better price-performance" |
| GP2 → GP3 | 20% | varies by size |
| S3 Standard → IA | 40% storage only | "save on everything" |
| RI 1yr Partial Upfront | 35% | "up to 72%" |
| SP 1yr No Upfront | 25% | "up to 66%" |
| Database SP 1yr No Upfront | 20% | "up to 35%" |
| ElastiCache Redis → Valkey | 20% 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": truewith 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 numberscalculation_inputs: Machine-parseable input valuespricing_source: One ofaws_pricing_api,verified_table,aws_cost_explorer,pricing_unknownpricing_api_query: The filters used (if source isaws_pricing_api)
Rule 7: Never Generate a Finding Without Raw API Evidence
Every finding MUST reference data from an actual AWS API response:
resource_idMUST come from an AWS API response (describe-instances, describe-volumes, etc.)instance_typeMUST 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:
| Domain | Cost Explorer Service Name |
|---|---|
| EC2 instances | Amazon Elastic Compute Cloud - Compute |
| EBS volumes | Amazon Elastic Compute Cloud - Compute |
| RDS | Amazon Relational Database Service |
| ElastiCache | Amazon ElastiCache |
| Lambda | AWS Lambda |
| S3 | Amazon Simple Storage Service |
| CloudWatch | AmazonCloudWatch |
| NAT Gateway | Amazon Elastic Compute Cloud - Compute |
| OpenSearch | Amazon OpenSearch Service |
| Redshift | Amazon Redshift |
| DynamoDB | Amazon DynamoDB |
| EFS | Amazon Elastic File System |
| SageMaker | Amazon SageMaker |
| EKS | Amazon Elastic Container Service for Kubernetes |
| Kinesis | Amazon Kinesis |
| MSK | Amazon Managed Streaming for Apache Kafka |
| Glue | AWS Glue |
| DocumentDB | Amazon DocumentDB (with MongoDB compatibility) |
| Neptune | Amazon Neptune |
| FSx | Amazon FSx |
If the finding's monthly_savings exceeds the service's actual monthly spend:
- Count resources in that service from your resource inventory
- 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)
- If 3+ resources in service → cap at 90% and add
"requires_validation": true - 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:
| Component | gp2 | gp3 | io2 |
|---|---|---|---|
| Storage | $0.10/GB | $0.08/GB | $0.125/GB |
| IOPS | Included (burst) | Free up to 3000, then $0.005/IOPS | Tiered: $0.065 (first 32K), $0.046 (32K-64K), $0.032 (>64K) per IOPS |
| Throughput | Included | Free up to 125 MB/s, then $0.04/MBps | Included |
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
MultiAZfield fromdescribe-db-instances - If
MultiAZ: true, query Pricing API withdeploymentOption=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
Platformfield fromdescribe-instances - If
Platform: windows→ query withoperatingSystem=Windows(typically 2× Linux price) - If
Platformis absent → query withoperatingSystem=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": trueto 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.3as 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: 0with"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 Key | Meaning |
|---|---|
aws:cloudformation:stack-name | CloudFormation managed |
Tags containing terraform | Terraform managed |
Tags containing pulumi | Pulumi managed |
If IaC tags found:
- Add
"managed_by_iac": trueto 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": falsein 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
| # | Mistake | Correct Approach |
|---|---|---|
| 1 | CW Logs: stored_gb × $0.50 | stored_gb × $0.03 (storage, not ingestion) |
| 2 | Savings > service spend | Verify resource count first, cap only if 3+ resources |
| 3 | Missing instance type → guess | monthly_savings=0, pricing_unknown=true |
| 4 | Missing metric → assume idle | Skip that signal, note as no_data |
| 5 | Creative downsize (m5→t3) | Same family, one size down only |
| 6 | NAT traffic composition guess | needs_manual_review=true |
| 7 | Windows priced as Linux | Query API with operatingSystem=Windows |
| 8 | Single-AZ price for Multi-AZ | Query API with deploymentOption=Multi-AZ |
| 9 | EBS storage only | Include IOPS + throughput costs |
| 10 | "Up to X%" percentages | Use fixed conservative rates |
| 11 | Interpolating sizes | Query Pricing API for exact type |
| 12 | us-east-1 table for other regions | Use Pricing API for non-us-east-1 |
| 13 | On-Demand price for Spot/RI | Check InstanceLifecycle and RI coverage |
| 14 | Delete IaC-managed resource | Flag for IaC team review |
Rules
- Only return confidence >= 50
- Include Name tags in
resource_name - Return
[]if no issues - Price resolution: API first → verified table → $0 with pricing_unknown
- Every finding needs calculation + pricing_source in details
- Sanity-check savings vs service billing (context-aware, not fixed cap)
- Flag findings > $100 for validation
- Missing CloudWatch data = skip signal, not zero
- Downsize: same family, one size down, verify target exists
- Data transfer composition: flag for manual review, not estimate
- Correct OS, deployment option, all EBS components
- No findings with monthly_savings between $0.01 and $0.99
- Check RI/SP coverage and Spot lifecycle before pricing
- Detect burstable instance credit patterns
- Flag IaC-managed resources for team review
- Handle Pricing API errors gracefully (retry then fallback)
- 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