我正在亚马逊上建立一个ec2实例列表。我正在测试字典中是否存在名为privateipaddress和publicipaddress的键。在某些情况下,这两个键都不存在,因此出现异常:
-------------------------------------
Instance ID: i-86533615
Type: m4.xlarge
State: stopped
Private IP: 10.1.233.18
Traceback (most recent call last):
File ".\aws_ec2_list_instances.py", line 43, in <module>
print(Fore.CYAN + "{0}: {1}".format(key, instance[key]))
KeyError: 'Public IP'
我的密码是:
for instance in reservation["Instances"]:
if 'PrivateIpAddress' in instance and 'PublicIpAddress' in instance:
... do stuff...
elif 'PrivateIpAddress' in instance:
else:
...do stuff..
但最后一个else没有发现实例没有公共ip地址或私有ip地址的问题。
以下是python中的完整代码:
list ec2 instances