Created
May 19, 2015 20:36
-
-
Save overdrive3000/b4724601c8e9fd5d1b77 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/python | |
import os | |
import time | |
import boto | |
import boto.manage.cmdshell | |
def launch_instance(ami='ami-a73264ce', | |
instance_type='t1.micro', | |
key_name='aws01-servers', | |
key_extension='.pem', | |
key_dir='~/keys', | |
group_name='sg-2f4fb640', | |
ssh_port=22, | |
cidr='0.0.0.0/0', | |
subnet='subnet-78c7d415', | |
tag='keystore_dev', | |
user_data=None, | |
cmd_shell=True, | |
login_user='ubuntu', | |
ssh_passwd=None): | |
""" | |
Crea una instancia, espera su ejecucion y retorna un hash con el objeto | |
de la instancia y el objeto CmdShell. | |
""" | |
cmd = None | |
ec2 = boto.connect_ec2() | |
try: | |
key = ec2.get_all_key_pairs(keynames=[key_name])[0] | |
except ec2.ResponseError, e: | |
if e.code == 'InvalidKeyPair.NotFound': | |
print 'Creating keypair: %s' % key_name | |
key = ec2.create_key_pair(key_name) | |
key.save(key_dir) | |
else: | |
raise | |
try: | |
group = ec2.get_all_security_groups(group_ids=[group_name])[0] | |
except ec2.ResponseError, e: | |
if e.code == 'InvalidGroup.NotFound': | |
print 'Creating Security Group: %s' % group_name | |
group = ec2.create_security_group(group_name, | |
'A test Sec Group') | |
else: | |
raise | |
try: | |
group.authorize('tcp', ssh_port, ssh_port, cidr) | |
except ec2.ResponseError, e: | |
if e.code == 'InvalidPermission.Duplicate': | |
print 'Security Group: %s already authorized' % group_name | |
else: | |
raise | |
interface = boto.ec2.networkinterface.NetworkInterfaceSpecification(subnet_id=subnet, | |
groups=[group_name], | |
associate_public_ip_address=True) | |
interface = boto.ec2.networkinterface.NetworkInterfaceCollection(interface) | |
reservation = ec2.run_instances(ami, | |
key_name=key_name, | |
instance_type=instance_type, | |
# subnet_id=subnet, | |
# security_group_ids=[group_name], | |
network_interfaces=interface, | |
user_data=user_data) | |
instance = reservation.instances[0] | |
print 'waiting for instance' | |
while instance.state != 'running': | |
print '.' | |
time.sleep(5) | |
instance.update() | |
print 'done' | |
instance.add_tag('Name', value=tag) | |
instance.add_tag('Description', value='Keystore Test Instance') | |
instance.add_tag('PONumber', value='PO001468') | |
if cmd_shell: | |
key_path = os.path.join(os.path.expanduser(key_dir), | |
key_name + key_extension) | |
print "Using Key %s" % key_path | |
cmd = boto.manage.cmdshell.sshclient_from_instance(instance, | |
key_path, | |
user_name=login_user | |
) | |
return (instance, cmd) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment