Created
November 5, 2013 20:21
-
-
Save ardeshir/7325523 to your computer and use it in GitHub Desktop.
AWS Python Tool
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
import os | |
import time | |
import boto | |
import boto.manage.cmdshell | |
def launch_instance(ami='ami-7341831a', | |
instance_type='t1.micro', | |
key_name='us-west-key2', | |
key_extention='.pem', | |
key_dir='~/Documents/Keys', | |
group_name='pyboto', | |
ssh_port='22', | |
cidr='0.0.0.0/0', | |
tag='pyboto', | |
user_data=None, | |
cmd_shell=True, | |
login_user='ec2-user', | |
ssh_passwd=None): | |
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(groupnames=[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 group that allows SSH access') | |
else: | |
raise | |
try: | |
group.authorize('tcp', ssh_port, http_port, cid) | |
except ec2.ResponseError, e: | |
if e.code == 'InvalidPermission.Duplicate': | |
print 'Security Group: %s already authorized' % group_name | |
else: | |
raise | |
reservation = ec2.run_instance(ami, | |
key_name=key_name, | |
security_group=[group_name], | |
instance_type=instance_type, | |
user_data=user_data) | |
instance = reservation.instance[0] | |
print 'waiting for instance' | |
while instance.state != 'running': | |
print '.' | |
time.sleep(5) | |
instance.update() | |
print 'done' | |
instance.add_tag(tag) | |
if cmd_shell: | |
key_path = os.path.join(os.path.expanduser(key_dir), | |
key_name+key_extention) | |
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