I'm building a list of EC2 instances in Amazon. And I am testing for the existence of keys called PrivateIpAddress and PublicIpAddress in a dictionary. In some cases neither key exists and I get an exception:
-------------------------------------
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'
My code says:
for instance in reservation["Instances"]:
if 'PrivateIpAddress' in instance and 'PublicIpAddress' in instance:
... do stuff...
elif 'PrivateIpAddress' in instance:
else:
...do stuff..
But the last else doesn't catch the problem of an instance not having either a public ip address or a private ip address.
Here is the full code in python: list ec2 instances