Last active
October 3, 2017 19:42
-
-
Save amalgjose/210658b3f0a44e67a6f6 to your computer and use it in GitHub Desktop.
Python Program for getting all the details of running instances and tagging the instances
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
__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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment