|
| 1 | +#!/usr/bin/env python |
| 2 | +import boto |
| 3 | +import boto.ec2 |
| 4 | +import os |
| 5 | +from optparse import OptionParser |
| 6 | +import sys |
| 7 | +import time |
| 8 | +import yaml |
| 9 | + |
| 10 | + |
| 11 | +dirname = os.path.abspath(os.path.dirname(__file__)) |
| 12 | +config = yaml.load(open(os.path.join(dirname,"config.yaml"), "r")) |
| 13 | + |
| 14 | +def getConnection(): |
| 15 | + return boto.ec2.connect_to_region(config['REGION'], \ |
| 16 | + aws_access_key_id = config['AWS_ACCESS_KEY_ID'], |
| 17 | + aws_secret_access_key = config['AWS_SECRET_ACCESS_KEY']) |
| 18 | + |
| 19 | +def launchInstance(ami): |
| 20 | + |
| 21 | + conn = getConnection() |
| 22 | + image = conn.get_image(ami) |
| 23 | + |
| 24 | + security_groups = ['basic_server',] |
| 25 | + |
| 26 | + reservation = image.run(key_name=config['KEY'], |
| 27 | + security_groups=security_groups, |
| 28 | + instance_type=config['INSTANCE_TYPE']) |
| 29 | + |
| 30 | + instance = reservation.instances[0] |
| 31 | + print instance |
| 32 | + instanceId=instance.id |
| 33 | + conn.create_tags([instanceId], |
| 34 | + {"Name": '%s' % (tag_to_instance or "instance_launched_with_boto")}) |
| 35 | + |
| 36 | + print "Spinning up instance for '%s'. Waiting for it to boot up." % (ami) |
| 37 | + while instance.state == 'pending': |
| 38 | + print "Instance state: %s" % (instance.state) |
| 39 | + time.sleep(10) |
| 40 | + instance.update() |
| 41 | + |
| 42 | + publicDnsName = instance.public_dns_name |
| 43 | + print "Instance is running, public dns : %s" % publicDnsName |
| 44 | + return publicDnsName,instanceId |
| 45 | + |
| 46 | + |
| 47 | + |
| 48 | +if __name__=='__main__': |
| 49 | + |
| 50 | + parser = OptionParser() |
| 51 | + parser.add_option('-a', '--ami', dest = 'ami', type = "string", |
| 52 | + help = 'The AMI from which the instance should be launched') |
| 53 | + parser.add_option('-t', '--tag', dest = 'tag', type = "string", |
| 54 | + help = 'Give a tag to the instance') |
| 55 | + (options, args) = parser.parse_args() |
| 56 | + |
| 57 | + ami = options.ami |
| 58 | + tag_to_instance = options.tag |
| 59 | + |
| 60 | +if not ami : |
| 61 | + print "Please provide the AMI to bring up the instance." |
| 62 | + sys.exit(1) |
| 63 | + |
| 64 | +#launching instance with the give AMI |
| 65 | +publicDnsName, instanceId = launchInstance(ami) |
0 commit comments