如何用Python编写Lambda通过AWS账单服务API下载账单文件?
实现Lambda函数调用AWS账单API下载账单文件的思路
Cost Explorer(CE)API主打成本聚合分析,没法直接拿到原始账单文件(比如月度详细CSV、成本使用报告CUR),所以得换用AWS Billing相关的API来实现。下面分两种常见账单类型给出具体思路:
一、明确目标账单类型及对应API
先搞清楚你要下载的是哪类账单:
- 月度详细账单CSV:用AWS Billing的
get_billing_dataAPI直接获取CSV内容 - 成本与使用报告(CUR):先通过CUR API获取报告存储路径,再用S3 API下载(CUR默认会自动同步到你指定的S3桶)
二、Lambda基础配置
- 运行环境:选Python 3.9/3.11这类AWS支持的稳定版本
- IAM权限:给Lambda执行角色加最小权限:
- 月度账单:
billing:GetBillingData - CUR报告:
cur:DescribeReportDefinitions+ CUR存储桶的s3:GetObject - 如果要把下载的文件存到自己的S3桶,再加
s3:PutObject
- 月度账单:
- 网络:默认公共网络即可,要是S3桶是私有桶,就配置VPC端点访问
三、Python代码实现
场景1:下载月度详细账单CSV
import boto3 def lambda_handler(event, context): # 初始化Billing客户端 billing_client = boto3.client('billing') # 指定要获取的账单月份,格式YYYY-MM billing_period = '2024-05' try: # 调用API获取账单CSV内容 response = billing_client.get_billing_data(BillingPeriod=billing_period) billing_csv = response['BillingData'] # 把CSV上传到指定S3桶(可选,也可以直接返回或处理内容) s3_client = boto3.client('s3') s3_client.put_object( Bucket='your-target-bucket', Key=f'billing/monthly/{billing_period}.csv', Body=billing_csv ) return f"成功下载并存储账单:{billing_period}" except Exception as e: return f"下载失败:{str(e)}"
场景2:下载成本与使用报告(CUR)
import boto3 def lambda_handler(event, context): cur_client = boto3.client('cur') s3_client = boto3.client('s3') # 获取CUR报告配置,找到目标报告 report_defs = cur_client.describe_report_definitions()['ReportDefinitions'] target_report = next(r for r in report_defs if r['ReportName'] == 'your-cur-report-name') s3_bucket = target_report['S3Bucket'] s3_prefix = target_report['S3Prefix'] # 列出指定前缀下的CUR文件,取最新的 objects = s3_client.list_objects_v2(Bucket=s3_bucket, Prefix=s3_prefix)['Contents'] latest_obj = sorted(objects, key=lambda x: x['LastModified'], reverse=True)[0] # 下载到Lambda临时目录(/tmp/最大10GB) local_file_path = f"/tmp/{latest_obj['Key'].split('/')[-1]}" s3_client.download_file(s3_bucket, latest_obj['Key'], local_file_path) # 可选:把文件转存到其他S3桶或处理内容 # s3_client.upload_file(local_file_path, 'another-bucket', f'cur/latest/{latest_obj["Key"].split("/")[-1]}') return f"成功下载CUR文件:{latest_obj['Key']}"
四、触发方式
- 手动测试:用Lambda控制台的测试事件直接触发
- 定时触发:用EventBridge(原CloudWatch Events)设置规则,比如每月1号凌晨触发下载上月账单
- 其他触发:比如API Gateway触发按需下载,或者S3事件联动
五、关键注意事项
- 权限最小化:别给Lambda执行角色加多余权限,避免安全风险
- 临时存储限制:Lambda的
/tmp/目录最大10GB,超大CUR文件建议直接通过S3 API处理,不要下载到本地 - 账单周期限制:月度账单只能获取已结束的月份,当前未结束的月份无法通过
get_billing_data获取 - CUR生成延迟:CUR报告一般在账单周期结束后3-5天生成,定时触发要留足够缓冲时间
- 异常处理:代码里要加捕获逻辑,比如API调用失败、报告不存在等情况,避免函数报错中断
内容的提问来源于stack exchange,提问作者Shubham
相关产品推荐
相关产品推荐

