Now a days most of the software engineers are using cloud services. Amazon is one of the key players among cloud service providers.
While dealing with the cloud services, we have to monitor the usage and billing periodically.
Otherwise, end of the month we may get huge bill because of some continuously running unused instances.
Since we can launch instances in multiple regions, it may become difficult to track all the running instances every day.

Here I developed a small piece of code in python that lists all the running EC2 instances (including EMR) and EBS volumes in all regions/specific regions.
This code also has a method to tag all the instances with your custom Tags.
Tagging helps in identifying machines used by different people/team in a shared environment.
If the number of instances are less, manual tagging is not a difficult task. But tagging large number of instances manually is a tedious task.
This program may help you in tagging any number of instances within few seconds.

__author__ = 'Amal G Jose'
import sys
import boto
class GetAllInstances(object):
def __init__(self):
self.aws_access_key = 'XXXXXXXXXXXXXXX'
self.aws_secret_key = 'XXXXXXXXXXXXXXX'
if self.aws_access_key == '' or self.aws_secret_key == '':
print 'Enter AWS access key and Secret Key'
exit()
##Method for getting the details of all the running instances
def get_all_running_instances(self, region):
try:
##Creating EC2 connection
conn = boto.ec2.connect_to_region(region,
aws_access_key_id=self.aws_access_key,
aws_secret_access_key=self.aws_secret_key)
##List all running EC2 instances
reservations = conn.get_all_reservations()
for reservation in reservations:
for instance in reservation.instances:
print region + ':', instance.id
##List all running volumes
for volume in conn.get_all_volumes():
print region + ':', volume.id
except:
print str(sys.exc_info()[0])
##Method for tagging all the instances
def tag_all_instances(self, region):
try:
tags = {}
tags['Name'] = 'CloudComputing'
tags['Owner'] = 'Amal G Jose'
conn = boto.ec2.connect_to_region(region,
aws_access_key_id=self.aws_access_key,
aws_secret_access_key=self.aws_secret_key)
##Tagging EC2 instances
reservations = conn.get_all_reservations()
for reservation in reservations:
for instance in reservation.instances:
print "Tagging EC2 instance " + instance.id
conn.create_tags(instance.id, tags)
##Tagging Volumes
for volume in conn.get_all_volumes():
print "Tagging volume " + volume.id
conn.create_tags(volume.id, tags)
except:
print str(sys.exc_info()[0])
def main(self):
try:
regions = ['ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1',
'us-east-1','us-west-1', 'us-west-2','eu-west-1', 'sa-east-1']
for region in regions:
self.get_all_running_instances(region)
self.tag_all_instances(region)
except:
print str(sys.exc_info()[0])
if __name__ == '__main__':
get_instance_details = GetAllInstances()
get_instance_details.main()

view raw
GetAllInstances.py
hosted with ❤ by GitHub