Reputation: 431
The script seen, it works but I noticed another issue which I would appreciate a hint how to fix. when it comes across an instance that is terminated it barffs, it seems to complete but at the very end it barffs. not sure if that will always be the results. I am wondering if a try/except will work here of I just need to skip. here is my code, but once it hits a terminated instance I this error. I think we have a few instances that rebuild themselves on a constant bases. I assume it is barffing because it can't find the vpc and or subnet.
I am thinking I need to pass them or ignore them but im kind of lost here..
EC2 State is: terminated
Traceback (most recent call last):
File "./list_ec2_instance.py.3", line 57, in <module>
main()
File "./list_ec2_instance.py.3", line 53, in main
list_instance()
File "./list_ec2_instance.py.3", line 37, in list_instance
print("VPC Id is: {}".format(instance_id['VpcId']))
KeyError: 'VpcId'
my code is:
for item in response['Reservations']:
#pprint(item['Instances'])
print("AWS Account ID: {}".format(item['OwnerId']))
for instance_id in item['Instances']:
#print(instance_id)
Tags = instance_id['Tags']
tag_name_value = ""
for tag in Tags:
if tag['Key'] == "Name":
tag_name_value = tag["Value"]
break
#Tags = instance_id['Tags']['Value']
State = instance_id['State']['Name']
#print("EC2 Name: {}".format(Tags))
print("EC2 Name: {}".format(tag_name_value))
print("Instance Id is: {}\nInstance Type is: {}".format(instance_id['InstanceId'],instance_id['InstanceType']))
print("EC2 State is: {}".format(State))
print("VPC Id is: {}".format(instance_id['VpcId']))
print("Subnet Id is: {}".format(instance_id['SubnetId']))
Upvotes: 0
Views: 312
Reputation: 238209
You can change this:
print("VPC Id is: {}".format(instance_id['VpcId']))
into
if 'VpcId' in instance_id:
print("VPC Id is: {}".format(instance_id['VpcId']))
Upvotes: 2