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

使用Boto3调用describe_instances()获取EC2公网IP报KeyError如何解决

错误原因
  • Association字段不是必现字段:只有分配了公网IP或弹性公网IP的EC2实例,弹性网卡下才会存在Association字段,私有子网内未配置公网IP的实例不存在该字段,直接硬编码访问就会触发KeyError异常。
  • 取值层级不完整:Association本身是字典类型,你需要的公网IP存储在该字典的PublicIp子属性中,直接取Association得到的是包含公网IP、IP所有者ID等信息的集合,并非最终需要的IP字符串。
  • 打印逻辑位置错误:你将打印语句放在了双层循环外侧,循环遍历过程中实例属性变量会被不断覆盖,最终仅能输出最后一个遍历到的实例信息,无法输出所有EC2实例的属性。
修正后可运行代码
import boto3

ec2client = boto3.client('ec2')
response = ec2client.describe_instances()

for reservation in response["Reservations"]:
    for instance in reservation["Instances"]:
        instance_id = instance["InstanceId"]
        instance_type = instance["InstanceType"]
        # 链式调用get方法避免KeyError,无公网IP时返回默认提示
        public_ip = instance.get("NetworkInterfaces", [{}])[0].get("Association", {}).get("PublicIp", "无公网IP")
        
        # 打印逻辑移入循环,逐台输出实例信息
        print(f"InstanceID: {instance_id}")
        print(f"InstanceType: {instance_type}")
        print(f"PublicIp: {public_ip}")
        print("="*40)
补充优化建议

如果实例存在多块弹性网卡,你可以遍历所有NetworkInterfaces,收集所有绑定的公网IP,避免只取第一块网卡漏记其他公网IP的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 13:45:01