【发布时间】:2020-06-17 04:02:29
【问题描述】:
我正在尝试通过 python 程序获取 ec2 信息,但我无法获取公共 ip 地址的值..尽管它附加了公共 ip,但打印为 None(我可以从控制台看到)
我尝试了什么:
inst_id = []
for reserv in res_inst['Reservations']:
instance = reserv['Instances']
for inst in instance:
ip_addr = inst['PrivateIpAddress']
#print(inst)
if (ip == ip_addr):
inst_id = inst['InstanceId']
inst_type = inst['InstanceType']
image_id = inst['ImageId']
vpc_id = inst['VpcId']
key_name = inst['KeyName']
#pub_ip = inst[u'PublicIpAddress']
pub_ip = inst.get(u'PublicIpAddress')
print(inst_type)
print(inst_id)
print(key_name)
print(vpc_id)
print(pub_ip)
print(image_id)
az = inst['Placement']['AvailabilityZone']
print(az)
for s1 in inst['SecurityGroups']:
sg_name = s1['GroupName']
print(sg_name)
在上面的代码中,这些语法不适用于公共 ip..它说关键错误
pub_ip = inst[u'PublicIpAddress']
pub_ip = inst['PublicIpAddress']
以下语法有效,但将 None 作为值
pub_ip = inst.get(u'PublicIpAddress')
输出:除了打印为 None 的 print(pub_ip) 之外,我得到了所有值。
我确信当我在上面的代码中打印inst 的整个 json 字符串时,我看到该 json 字典中存在公共 ip 值,但是,当打印它时说 None。
谁能建议我在这里做错了什么...
【问题讨论】:
-
可能真的没有。当 ec2 位于私有子网时,它不会有公共子网。
标签: python json amazon-web-services amazon-ec2 boto3