samedi 7 mars 2015

AWS Launch instance script boto python

I am currently working my way through the Python and AWS cookbook from O'Reilly publishing I currently on the launch instance script which I had working (Which funny story I didnt think was working till I clicked on another region in AWS ) and saw I had created around 50 instance trying to get script working...Lesson for new people to AWS always set and know your default region).


But know for some reason the script seems to run without any errors but in the interactive python shell nothing seems to print out and no instances are created I dont know what I have changed to stop this working and from some testing I have done basically import boto in interactive mode and connect to EC2 from there seems to successfully connect so I have no idea what is causing this. The script is below so if anyone can help that would be great or any tests if i can do:



import os
import time
import boto
import boto.manage.cmdshell

def launch_instance(ami="i-7ef58184",
instance_type="t1.micro",
key_name="paws",
key_extension=".pem",
key_dir="~/.ssh",
group_name="paws",
ssh_port="22",
cidr="0.0.0.0/0",
tag="paws",
user_data=None,
cmd_shell=True,
login_user="ec2-user",
ssh_passwd=None):
cmd = None

ec2 = boto.connect_ec2() # Crededentials are stored in /etc/boto.cfg
ec2 = boto.connect_ec2(debug=2)
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,ssh_port,cidr)
except ec2.ResponseError, e:
if e.code == 'InvalidPermission.Duplicate':
print ('Security group %s already authorized') % group_name
else:
raise
reservation = ec2.run_instances(ami,
key_name=key_name,
security_groups=[group_name],
instance_type=instance_type,
user_data=user_data)
instance = reservation.instances[0]
print 'waiting for instance...'
while instance.state != 'running':
time.sleep(30)
instance.update()
print 'Instance is now running'
print 'Instance IP is %s' % instance.ip_address
instance.add_tag(tag)


if cmd_shell:
key_path = os.path.join(os.path.expanduser(key_dir),
key_name+key_extension)
cmd = boto.manage.sshclient_from_instance(instance,
key_path,
username=login_user)
return (instance, cmd)


Can anyone anyone help?





Aucun commentaire:

Enregistrer un commentaire