如何在Python脚本中实现AWS Top3高成本服务的资源级成本细分?
实现AWS资源级成本细分的方案
核心思路
通过AWS Cost Explorer API(借助boto3的costexplorer客户端),先按服务维度聚合获取Top3高成本服务,再针对每个服务的特定资源维度(如EC2的InstanceId、S3的BucketName、RDS的DBInstanceIdentifier)发起二次查询,从而拿到资源级的成本明细。
具体实现步骤
1. 初始化boto3客户端
确保环境已配置AWS凭证(环境变量、~/.aws/credentials等),初始化Cost Explorer客户端:
import boto3 from datetime import datetime, timedelta # Cost Explorer为全局服务,固定使用us-east-1区域即可 ce_client = boto3.client('ce', region_name='us-east-1')
2. 获取过去6个月的Top3服务成本
按SERVICE维度聚合成本,排序后提取Top3:
# 计算时间范围:过去6个月 end_date = datetime.today().strftime('%Y-%m-%d') start_date = (datetime.today() - timedelta(days=180)).strftime('%Y-%m-%d') # 查询按服务划分的成本数据 response = ce_client.get_cost_and_usage( TimePeriod={'Start': start_date, 'End': end_date}, Granularity='MONTHLY', # 按需可改为DAILY Metrics=['UnblendedCost'], GroupBy=[{'Type': 'DIMENSION', 'Key': 'SERVICE'}] ) # 整理服务成本数据并排序 service_costs = [] for group in response['ResultsByTime'][0]['Groups']: service_name = group['Keys'][0] cost = float(group['Metrics']['UnblendedCost']['Amount']) service_costs.append({'service': service_name, 'cost': cost}) # 按成本降序排序,取Top3服务 top3_services = sorted(service_costs, key=lambda x: x['cost'], reverse=True)[:3]
3. 针对不同服务查询资源级成本明细
定义服务与对应资源维度的映射,循环处理每个Top服务:
# 服务-资源维度映射表,可按需扩展其他服务 service_dimension_map = { 'Amazon Elastic Compute Cloud - Compute': 'InstanceId', 'Amazon Simple Storage Service': 'BucketName', 'Amazon Relational Database Service': 'DBInstanceIdentifier', 'Amazon Lambda': 'FunctionName' } # 遍历Top3服务,查询对应资源级成本 for service in top3_services: service_name = service['service'] dimension_key = service_dimension_map.get(service_name) if not dimension_key: print(f"暂不支持获取{service_name}的资源级成本明细") continue # 查询该服务的资源级成本数据 resource_response = ce_client.get_cost_and_usage( TimePeriod={'Start': start_date, 'End': end_date}, Granularity='MONTHLY', Metrics=['UnblendedCost'], GroupBy=[ {'Type': 'DIMENSION', 'Key': 'SERVICE'}, {'Type': 'DIMENSION', 'Key': dimension_key} ], Filter={ 'Dimensions': { 'Key': 'SERVICE', 'Values': [service_name] } } ) # 整理并输出资源级成本明细 print(f"\n=== {service_name} 资源级成本明细(过去6个月) ===") for group in resource_response['ResultsByTime'][0]['Groups']: resource_id = group['Keys'][1] cost = float(group['Metrics']['UnblendedCost']['Amount']) print(f"资源ID: {resource_id} | 总成本: ${cost:.2f}")
4. 关键注意事项
- 权限配置:执行脚本的IAM角色/用户需拥有
ce:GetCostAndUsage权限,可通过以下IAM策略授权:{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "ce:GetCostAndUsage", "Resource": "*" } ] } - 维度可用性:部分AWS服务可能未公开资源级维度,需参考AWS官方文档确认对应服务支持的维度列表。
- 数据延迟:Cost Explorer的数据存在24-48小时的延迟,无法获取实时成本数据。
内容的提问来源于stack exchange,提问作者Surya Appana
相关产品推荐
相关产品推荐

