Python调用AWS Resource Explorer获取全量资源:节流与分页问题求助
解决方案:获取AWS Resource Explorer全量资源并导出到S3 CSV
核心问题拆解
- 控制台默认分页限制导致仅能查看部分资源
- API调用触发
ThrottlingException:AWS对Resource Explorer API有请求速率限制,短时间内请求量超标会被限流 - 现有代码未处理分页逻辑,仅获取第一页数据
分步解决方法
1. 配置API请求重试策略
通过boto3内置的重试机制处理节流异常,设置指数退避规则,避免因限流中断请求。
2. 实现全量资源分页获取
list_resources API返回结果包含NextToken,循环调用该接口直到NextToken为空,即可拉取所有资源。
3. 转换为CSV格式并上传到S3
将收集到的资源数据整理成CSV结构,再通过boto3的S3客户端上传文件。
完整代码实现
import boto3 from botocore.config import Config import csv from io import StringIO def get_all_resource_explorer_resources(): # 配置自适应重试策略,处理节流异常 config = Config( retries={ 'max_attempts': 5, 'mode': 'adaptive' } ) resource_explorer = boto3.client('resource-explorer-2', config=config) all_resources = [] next_token = None while True: request_kwargs = {'NextToken': next_token} if next_token else {} try: response = resource_explorer.list_resources(**request_kwargs) all_resources.extend(response['Resources']) next_token = response.get('NextToken') if not next_token: break except resource_explorer.exceptions.ThrottlingException as e: print(f"触发节流,自动重试: {e}") return all_resources def resources_to_csv(resources): if not resources: return "" # 自定义CSV字段,可根据需求调整 fieldnames = ['Arn', 'Name', 'ResourceType', 'Region', 'Service'] output_buffer = StringIO() csv_writer = csv.DictWriter(output_buffer, fieldnames=fieldnames) csv_writer.writeheader() for resource in resources: csv_writer.writerow({ 'Arn': resource['Arn'], 'Name': resource.get('Name', ''), 'ResourceType': resource['ResourceType'], 'Region': resource['Region'], 'Service': resource['ResourceType'].split(':')[0] }) return output_buffer.getvalue() def upload_csv_to_s3(csv_content, bucket_name, s3_file_key): s3_client = boto3.client('s3') s3_client.put_object( Bucket=bucket_name, Key=s3_file_key, Body=csv_content, ContentType='text/csv' ) print(f"CSV已上传至S3:s3://{bucket_name}/{s3_file_key}") if __name__ == "__main__": # 替换为你的S3桶名和目标文件路径 TARGET_S3_BUCKET = "your-bucket-name" TARGET_S3_KEY = "aws-resources-inventory.csv" # 获取全量资源 all_resources = get_all_resource_explorer_resources() print(f"共获取到{len(all_resources)}条资源") # 转换为CSV格式 csv_data = resources_to_csv(all_resources) # 上传到S3 upload_csv_to_s3(csv_data, TARGET_S3_BUCKET, TARGET_S3_KEY)
关键注意事项
- 重试策略:
adaptive模式会根据错误类型自动调整重试间隔,针对节流异常效果最优;max_attempts可根据实际情况调整(建议3-5次) - 字段自定义:CSV的
fieldnames可按需添加或修改,比如补充OwningAccountId等字段 - 权限要求:执行代码的IAM角色需要具备
resource-explorer-2:ListResources和s3:PutObject权限 - 性能适配:500-1000条资源用单线程完全足够,若资源量极大可考虑分批次写入或多线程处理
内容的提问来源于stack exchange,提问作者Anjum aara
相关产品推荐
相关产品推荐

