You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Boto3获取所有区域EC2详情仅显示最后一个区域数据如何处理

问题原因
  • result数组初始化放在了区域遍历循环内部,每次处理新区域时都会清空之前所有区域的查询结果
  • 为每个区域创建了专属client后,调用describe_instances时仍使用了全局未指定区域的ec2客户端,实际没有按区域查询数据
  • 文件写入用的是w覆盖模式,每次遍历区域都会覆盖之前生成的CSV文件,最终仅保留最后一次写入的内容
  • 原代码中查询区域的方法名拼写错误,应为describe_regions而非describe_region
  • 硬编码了InstanceIds参数,若要查询对应区域所有EC2实例需要移除该参数
修正后完整代码
import boto3
import csv

# 初始化全局EC2客户端用于拉取区域列表
ec2 = boto3.client(service_name='ec2')
# 拉取所有区域名称
regions = [each_region['RegionName'] for each_region in ec2.describe_regions()['Regions']]

# 把result初始化放到循环外,累计所有区域的结果
result = []
header = ['ImageId', 'InstanceType', 'PublicIp', 'PrivateIp']

for each_region in regions:
    # 使用对应区域的客户端查询
    client = boto3.client('ec2', region_name=each_region)
    # 移除InstanceIds参数查询该区域所有实例,若需查指定实例可自行加回该参数
    response = client.describe_instances().get('Reservations', [])
    
    for item in response:
        for each in item['Instances']:
            # 处理没有公网IP的实例避免取值报错
            public_ip = each.get('PublicIpAddress', '')
            private_ip = each.get('PrivateIpAddress', '')
            result.append({
                'ImageId': each['ImageId'],
                'InstanceType': each['InstanceType'],
                'PublicIp': public_ip,
                'PrivateIp': private_ip
            })

# 文件写操作放到循环外,只写入一次所有累计的结果
with open('ec2-details.csv', 'w', newline='', encoding='utf-8') as file:
    writer = csv.DictWriter(file, fieldnames=header)
    writer.writeheader()
    writer.writerows(result)

内容的提问来源于stack exchange,提问作者Joel P

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 09:24:08