aws-cost-optimize

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

AWS Cost Optimize

AWS成本优化

This workflow analyzes Infrastructure-as-Code (IaC) files and AWS resources to generate cost optimization recommendations. It creates individual GitHub issues for each optimization opportunity plus one EPIC issue to coordinate implementation, enabling efficient tracking and execution of cost savings initiatives.
本工作流分析基础设施即代码(IaC)文件和AWS资源,生成成本优化建议。它会为每个优化机会创建单独的GitHub Issue,并创建一个EPIC Issue来协调实施,从而实现成本节约举措的高效跟踪与执行。

Prerequisites

前提条件

  • AWS CLI configured and authenticated (
    aws sts get-caller-identity
    succeeds)
  • GitHub MCP server configured and authenticated
  • Target GitHub repository identified
  • AWS resources deployed (IaC files optional but helpful)
  • AWS CLI已配置并完成认证(
    aws sts get-caller-identity
    执行成功)
  • GitHub MCP服务器已配置并完成认证
  • 已确定目标GitHub仓库
  • 已部署AWS资源(IaC文件为可选,但有助于分析)

Workflow Steps

工作流步骤

Step 1: Get AWS Cost Optimization Best Practices

步骤1:获取AWS成本优化最佳实践

Action: Retrieve cost optimization best practices before analysis Tools:
fetch
to retrieve AWS documentation Process:
  1. Load Best Practices:
    • Fetch
      https://docs.aws.amazon.com/cost-management/latest/userguide/cost-optimization-best-practices.html
    • Fetch the AWS Well-Architected Cost Optimization pillar summary
    • Use these practices to inform subsequent analysis and recommendations
操作:在分析前获取成本优化最佳实践 工具:使用
fetch
获取AWS文档 流程:
  1. 加载最佳实践:
    • 获取
      https://docs.aws.amazon.com/cost-management/latest/userguide/cost-optimization-best-practices.html
    • 获取AWS架构完善框架成本优化支柱摘要
    • 利用这些实践指导后续分析与建议生成

Step 2: Discover AWS Infrastructure

步骤2:发现AWS基础设施

Action: Dynamically discover and analyze AWS resources and configurations Tools: AWS CLI + Local file system access Process:
  1. Account & Region Discovery:
    • Execute
      aws sts get-caller-identity
      to confirm account
    • Execute
      aws configure get region
      to determine default region
  2. Resource Discovery (per region):
    • EC2 instances:
      aws ec2 describe-instances --query 'Reservations[].Instances[].[InstanceId,InstanceType,State.Name,Tags]'
    • RDS instances:
      aws rds describe-db-instances --query 'DBInstances[].[DBInstanceIdentifier,DBInstanceClass,Engine,MultiAZ]'
    • Lambda functions:
      aws lambda list-functions --query 'Functions[].[FunctionName,Runtime,MemorySize,Architectures]'
    • ECS clusters/services:
      aws ecs list-clusters
      then
      aws ecs describe-services
    • S3 buckets:
      aws s3api list-buckets --query 'Buckets[].Name'
    • ElastiCache clusters:
      aws elasticache describe-cache-clusters
    • NAT Gateways:
      aws ec2 describe-nat-gateways
    • Load Balancers:
      aws elbv2 describe-load-balancers
  3. IaC Detection:
    • Scan for IaC files:
      **/*.tf
      ,
      **/*.yaml
      (CloudFormation/SAM),
      **/*.json
      (CloudFormation),
      **/cdk.json
      ,
      lib/**/*.ts
      (CDK)
    • Parse resource definitions to understand intended configurations
    • Do NOT use application code files — only IaC files as the source of truth
    • If no IaC files found: STOP and report to user
操作:动态发现并分析AWS资源与配置 工具:AWS CLI + 本地文件系统访问权限 流程:
  1. 账户与区域发现:
    • 执行
      aws sts get-caller-identity
      确认账户
    • 执行
      aws configure get region
      确定默认区域
  2. 资源发现(按区域):
    • EC2实例:
      aws ec2 describe-instances --query 'Reservations[].Instances[].[InstanceId,InstanceType,State.Name,Tags]'
    • RDS实例:
      aws rds describe-db-instances --query 'DBInstances[].[DBInstanceIdentifier,DBInstanceClass,Engine,MultiAZ]'
    • Lambda函数:
      aws lambda list-functions --query 'Functions[].[FunctionName,Runtime,MemorySize,Architectures]'
    • ECS集群/服务:先执行
      aws ecs list-clusters
      再执行
      aws ecs describe-services
    • S3存储桶:
      aws s3api list-buckets --query 'Buckets[].Name'
    • ElastiCache集群:
      aws elasticache describe-cache-clusters
    • NAT网关:
      aws ec2 describe-nat-gateways
    • 负载均衡器:
      aws elbv2 describe-load-balancers
  3. IaC检测:
    • 扫描IaC文件:
      **/*.tf
      **/*.yaml
      (CloudFormation/SAM)、
      **/*.json
      (CloudFormation)、
      **/cdk.json
      lib/**/*.ts
      (CDK)
    • 解析资源定义以了解预期配置
    • 请勿使用应用代码文件——仅将IaC文件作为事实来源
    • 若未找到IaC文件:停止流程并向用户报告

Step 3: Collect Usage Metrics & Validate Current Costs

步骤3:收集使用指标与验证当前成本

Action: Gather utilization data and verify actual resource costs Tools: AWS CLI (CloudWatch, Cost Explorer) Process:
  1. CloudWatch Metrics (last 7 days):
    bash
    # EC2 CPU utilization
    aws cloudwatch get-metric-statistics \
      --namespace AWS/EC2 --metric-name CPUUtilization \
      --dimensions Name=InstanceId,Value=<id> \
      --start-time $(date -u -d '7 days ago' +%Y-%m-%dT%H:%M:%SZ) \
      --end-time $(date -u +%Y-%m-%dT%H:%M:%SZ) \
      --period 3600 --statistics Average
    
    # Lambda duration
    aws cloudwatch get-metric-statistics \
      --namespace AWS/Lambda --metric-name Duration \
      --dimensions Name=FunctionName,Value=<name> \
      --start-time $(date -u -d '7 days ago' +%Y-%m-%dT%H:%M:%SZ) \
      --end-time $(date -u +%Y-%m-%dT%H:%M:%SZ) \
      --period 86400 --statistics Average,Maximum
  2. AWS Cost Explorer:
    bash
    aws ce get-cost-and-usage \
      --time-period Start=$(date -u -d '30 days ago' +%Y-%m-%d),End=$(date -u +%Y-%m-%d) \
      --granularity MONTHLY --metrics BlendedCost \
      --group-by Type=DIMENSION,Key=SERVICE
  3. Calculate Baseline Metrics: CPU/Memory averages, Lambda invocation rates, data transfer patterns, and a realistic current monthly total.
操作:收集利用率数据并验证实际资源成本 工具:AWS CLI(CloudWatch、Cost Explorer) 流程:
  1. CloudWatch指标(最近7天):
    bash
    # EC2 CPU利用率
    aws cloudwatch get-metric-statistics \
      --namespace AWS/EC2 --metric-name CPUUtilization \
      --dimensions Name=InstanceId,Value=<id> \
      --start-time $(date -u -d '7 days ago' +%Y-%m-%dT%H:%M:%SZ) \
      --end-time $(date -u +%Y-%m-%dT%H:%M:%SZ) \
      --period 3600 --statistics Average
    
    # Lambda执行时长
    aws cloudwatch get-metric-statistics \
      --namespace AWS/Lambda --metric-name Duration \
      --dimensions Name=FunctionName,Value=<name> \
      --start-time $(date -u -d '7 days ago' +%Y-%m-%dT%H:%M:%SZ) \
      --end-time $(date -u +%Y-%m-%dT%H:%M:%SZ) \
      --period 86400 --statistics Average,Maximum
  2. AWS Cost Explorer:
    bash
    aws ce get-cost-and-usage \
      --time-period Start=$(date -u -d '30 days ago' +%Y-%m-%d),End=$(date -u +%Y-%m-%d) \
      --granularity MONTHLY --metrics BlendedCost \
      --group-by Type=DIMENSION,Key=SERVICE
  3. 计算基准指标:CPU/内存平均值、Lambda调用率、数据传输模式,以及真实的当前月度总成本。

Step 4: Generate Cost Optimization Recommendations

步骤4:生成成本优化建议

Action: Analyze resources to identify optimization opportunities Process:
  1. Apply Optimization Patterns:
    Compute:
    • EC2: Right-size based on CPU/memory (<20% average → downsize), convert On-Demand to Savings Plans, migrate to Graviton/ARM (up to 40% cheaper)
    • Lambda: Reduce memory for idle functions, switch to
      arm64
      (20% cheaper)
    • ECS/EKS: Use Fargate Spot for dev/batch workloads
    Database:
    • RDS: Right-size instance class, convert single-AZ for dev, use Aurora Serverless v2 for variable load
    • DynamoDB: Switch Provisioned → On-Demand for unpredictable traffic
    • ElastiCache: Right-size node type based on memory utilization
    Storage:
    • S3: Lifecycle policies (Standard → Standard-IA after 30d → Glacier after 90d), enable Intelligent-Tiering
    • EBS: Delete unattached volumes, convert gp2 → gp3 (same performance, 20% cheaper)
    Network:
    • Consolidate NAT Gateways for non-production environments
    • Use VPC endpoints for S3/DynamoDB to avoid NAT Gateway charges
  2. Calculate Priority Score:
    Priority Score = (Value Score × Monthly Savings) / (Risk Score × Implementation Days)
    High: Score > 20 | Medium: Score 5-20 | Low: Score < 5
操作:分析资源以识别优化机会 流程:
  1. 应用优化模式:
    计算资源:
    • EC2:基于CPU/内存使用率调整实例规格(平均使用率<20%→降配),按需实例转换为Savings Plans,迁移至Graviton/ARM架构(最高节省40%成本)
    • Lambda:为闲置函数降低内存配置,切换至
      arm64
      架构(节省20%成本)
    • ECS/EKS:为开发/批处理工作负载使用Fargate Spot
    数据库:
    • RDS:调整实例规格,开发环境转换为单AZ部署,可变负载场景使用Aurora Serverless v2
    • DynamoDB:不可预测流量场景从预配置模式切换至按需模式
    • ElastiCache:基于内存使用率调整节点类型
    存储:
    • S3:配置生命周期策略(30天后从标准存储转换为标准低频访问存储→90天后转换为Glacier存储),启用智能分层
    • EBS:删除未挂载卷,将gp2转换为gp3(性能相同,成本降低20%)
    网络:
    • 整合非生产环境的NAT网关
    • 使用VPC端点访问S3/DynamoDB以避免NAT网关费用
  2. 计算优先级评分:
    优先级评分 = (价值评分 × 月度节省金额) / (风险评分 × 实施天数)
    高:评分>20 | 中:评分5-20 | 低:评分<5

Step 5: User Confirmation

步骤5:用户确认

Action: Present summary and get approval before creating GitHub issues
🎯 AWS Cost Optimization Summary

📊 Analysis Results:
• Total Resources Analyzed: X
• Current Monthly Cost: $X
• Potential Monthly Savings: $Y
• Optimization Opportunities: Z
• High Priority Items: N

🏆 Recommendations:
1. [Resource]: [Current] → [Target] = $X/month savings - [Risk] | [Effort]
...

💡 This will create Y individual GitHub issues + 1 EPIC issue.

❓ Proceed with creating GitHub issues? (y/n)
Wait for user confirmation before proceeding.
操作:展示摘要并在创建GitHub Issue前获取用户批准
🎯 AWS成本优化摘要

📊 分析结果:
• 分析的资源总数: X
• 当前月度成本: $X
• 潜在月度节省金额: $Y
• 优化机会数量: Z
• 高优先级项数量: N

🏆 建议:
1. [资源类型]: [当前配置] → [目标配置] = 月度节省$X - [风险等级] | [实施工作量]
...

💡 此操作将创建Y个独立GitHub Issue + 1个EPIC Issue。

❓ 是否继续创建GitHub Issue?(y/n)
等待用户确认后再继续。

Step 6: Create Individual Optimization Issues

步骤6:创建单个优化Issue

Action: Create separate GitHub issues for each optimization. Label with "cost-optimization" (green) and "aws" (orange).
Title:
[COST-OPT] [Resource Type] - [Brief Description] - $X/month savings
Body:
markdown
undefined
操作:为每个优化项创建单独的GitHub Issue。添加标签"cost-optimization"(绿色)和"aws"(橙色)。
标题:
[COST-OPT] [资源类型] - [简要描述] - 月度节省$X
正文:
markdown
undefined

💰 Cost Optimization: [Brief Title]

💰 成本优化:[简要标题]

Monthly Savings: $X | Risk Level: [Low/Medium/High] | Effort: X days
月度节省: $X | 风险等级: [低/中/高] | 实施工作量: X天

📋 Description

📋 描述

[Clear explanation of the optimization and why it's needed]
[清晰说明优化内容及必要性]

🔧 Implementation

🔧 实施步骤

IaC Files Detected: [Yes/No]
bash
undefined
检测到IaC文件: [是/否]
bash
undefined

IaC modification (preferred) or AWS CLI fallback

首选IaC修改方案,或备选AWS CLI命令

undefined
undefined

📊 Evidence

📊 依据

  • Current Configuration: [details]
  • Usage Pattern: [evidence from CloudWatch]
  • Cost Impact: $X/month → $Y/month
  • 当前配置: [详情]
  • 使用模式: [来自CloudWatch的证据]
  • 成本影响: 月度$X → 月度$Y

✅ Validation Steps

✅ 验证步骤

  • Test in non-production environment
  • Verify no performance degradation via CloudWatch
  • Confirm cost reduction in AWS Cost Explorer
  • 在非生产环境测试
  • 通过CloudWatch验证无性能下降
  • 在AWS Cost Explorer确认成本降低

⚠️ Risks & Considerations

⚠️ 风险与注意事项

  • [Risk and mitigation]
Priority Score: X | Value: X/10 | Risk: X/10
undefined
  • [风险及缓解措施]
优先级评分: X | 价值: X/10 | 风险: X/10
undefined

Step 7: Create EPIC Coordinating Issue

步骤7:创建EPIC协调Issue

Action: Create master tracking issue. Label with "cost-optimization" (green), "aws" (orange), "epic" (purple).
Title:
[EPIC] AWS Cost Optimization Initiative - $X/month potential savings
Body: Executive summary with account/region details, Mermaid architecture diagram of current resources, prioritized checklist linking all individual issues (High → Medium → Low), progress tracking, and success criteria (>80% of estimated savings realized, no performance degradation).
操作:创建主追踪Issue。添加标签"cost-optimization"(绿色)、"aws"(橙色)、"epic"(紫色)。
标题:
[EPIC] AWS成本优化计划 - 潜在月度节省$X
正文:包含账户/区域详情的执行摘要、当前资源的Mermaid架构图、按优先级排序的所有单个Issue链接清单(高→中→低)、进度跟踪以及成功标准(实现预估节省金额的80%以上,无性能下降)。

Error Handling

错误处理

  • AWS Authentication Failure: Guide through
    aws configure
  • No Resources Found: Create informational issue about AWS resource deployment
  • Insufficient Permissions: List required IAM read-only permissions
  • GitHub Creation Failure: Output formatted recommendations to console
  • Cost Explorer Not Enabled: Guide user to enable in AWS Console
  • AWS认证失败: 引导用户执行
    aws configure
  • 未找到资源: 创建关于AWS资源部署的信息性Issue
  • 权限不足: 列出所需的IAM只读权限
  • GitHub Issue创建失败: 将格式化建议输出至控制台
  • Cost Explorer未启用: 引导用户在AWS控制台启用

Success Criteria

成功标准

  • ✅ All cost estimates verified against actual configurations and AWS pricing
  • ✅ Individual GitHub issues created for each optimization
  • ✅ EPIC issue provides comprehensive coordination and tracking
  • ✅ All recommendations include specific AWS CLI or IaC commands
  • ✅ User confirmation obtained before creating issues
  • ✅ 所有成本估算均已根据实际配置和AWS定价验证
  • ✅ 为每个优化项创建了单独的GitHub Issue
  • ✅ EPIC Issue提供了全面的协调与跟踪功能
  • ✅ 所有建议均包含具体的AWS CLI或IaC命令
  • ✅ 创建Issue前已获取用户确认