I use custom tags for my AWS instances. I am trying to list all the instances (running and stopped) in CSV file. Not being a programmer, I searched and copied/pasted codes and came with a script which runs well. But I have noticed that if one tag is missing then the script throws an error and stops right there. If the tag is created but is empty, then the script prints a blank space, but if the tag is not created at all then the script just stops. For example if the tag Owner is missing then it throws an error KeyError: 'Owner' and stops there. My script is pasted below. Can somebody let me know what changes I need to make so that if the tag does not exist, the script prints out N/A instead of stopping.
#!/usr/bin/env python
import boto.ec2
from boto.ec2 import EC2Connection
csv_file = open('/home/sbasnet/Scripts/Instances/instances_east.csv','w+')
def process_instance_list(connection):
map(build_instance_list,connection.get_all_instances())
def build_instance_list(reservation):
map(write_instances,reservation.instances)
def write_instances(instance):
if (instance.platform == 'windows'):
platform = 'Windows'
else:
platform = 'Linux'
csv_file.write("%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\n"%(instance.id,instance.private_ip_address,instance.tags['Classification'],instance.tags['FQDN'],instance.tags['Owner'],instance.tags['RunType'],instance.instance_type,instance.subnet_id,instance.key_name,platform,instance.placement))
csv_file.flush()
if __name__=="__main__":
connection = EC2Connection(aws_access_key_id='ACCESS',aws_secret_access_key='SECRET')
process_instance_list(connection)
csv_file.close()
TIA sbasnet
Aucun commentaire:
Enregistrer un commentaire