如何通过Python脚本按资源标签统计AWS各资源上月成本?
实现按标签统计AWS单个资源成本的方法
核心思路
利用AWS Cost Explorer API的分组聚合能力,直接指定标签维度(比如Name)来拆分单个资源的成本,同时可过滤目标服务,最终解析返回数据得到标签对应的成本结果。
具体实现步骤
1. 准备依赖与权限
- 安装AWS Python SDK:
pip install boto3 - 确保AWS账号拥有
ce:GetCostAndUsage权限,且已配置好凭证(环境变量、~/.aws/credentials配置文件均可)
2. 修改Python脚本代码
以下是针对RDS服务、按Name标签统计上月成本的可运行示例:
import boto3 from datetime import datetime, timedelta def get_tagged_resource_costs(target_service, target_tag): ce_client = boto3.client('ce') # 自动计算上月的起止日期 today = datetime.today() last_month_first_day = (today.replace(day=1) - timedelta(days=1)).replace(day=1) last_month_last_day = today.replace(day=1) - timedelta(days=1) # 调用Cost Explorer API获取成本数据 cost_response = ce_client.get_cost_and_usage( TimePeriod={ 'Start': last_month_first_day.strftime('%Y-%m-%d'), 'End': last_month_last_day.strftime('%Y-%m-%d') }, Granularity='MONTHLY', Metrics=['UnblendedCost'], GroupBy=[ {'Type': 'TAG', 'Key': target_tag}, {'Type': 'DIMENSION', 'Key': 'SERVICE'} ], Filter={ 'Dimensions': { 'Key': 'SERVICE', 'Values': [target_service] } } ) # 解析并整理结果 resource_costs = {} for group in cost_response['ResultsByTime'][0]['Groups']: # 提取标签值 tag_value = next(k.split(':')[-1] for k in group['Keys'] if k.startswith(f'TAG:{target_tag}')) # 提取成本金额(保留两位小数) cost_amount = f"{float(group['Metrics']['UnblendedCost']['Amount']):.2f}$" resource_costs[tag_value] = cost_amount # 输出最终结果 for res_name, cost in resource_costs.items(): print(f"{res_name} - {cost}") # 调用示例:统计RDS服务按Name标签的上月成本 if __name__ == '__main__': get_tagged_resource_costs('Amazon Relational Database Service', 'Name')
3. 代码细节说明
- 时间范围:自动计算上月起止日期,无需手动输入
- 分组逻辑:同时按标签和服务维度分组,确保只统计目标服务下的带标签资源
- 成本指标:使用
UnblendedCost(非混合成本),与实际账单显示的成本一致 - 扩展性:如果要统计所有服务的标签成本,删除
Filter参数即可;更换标签键只需修改target_tag参数
内容的提问来源于stack exchange,提问作者Bhavesh R
相关产品推荐
相关产品推荐

