lundi 28 septembre 2015

Spin a instance in VPC from a AMI

I have the following code which basically creates a AMI of a instance.. i need to launch a same instance from this AMI in exact same region, subnet, VPC etc.. i.e same copy of original instance.

import boto.ec2
import time
import sys 
conn = boto.ec2.connect_to_region("ap-southeast-1")

reservations=conn.get_all_instances(sys.argv[1])
instances = [i for r in reservations for i in r.instances]
for i in instances:
#    print(i.__dict__)
    print "The",i,"has the following attributes:"
    a = i.image_id
    b = i.vpc_id
    c = i.key_name
    d = i.region
    e = i.subnet_id
#print a
#print "========"

ami_id = conn.create_image(sys.argv[1], "nitis", description="Testing", no_reboot=True, block_device_mapping=None, dry_run=False)
##image = conn.get_all_images(image_ids=[image_id])[0]

print "The new AMI is being created with id -->  %s" %ami_id

image = conn.get_image(ami_id)
while image.state == 'pending':
    time.sleep(10)
    image = conn.get_image(ami_id)
    #image.update()
    print "AMI still pending.. waiting 10 more sec!!! state:%s" % (image.state) 

if image.state == 'available':
   print "AMI CREATED SUCCESSFULLY with AMI id = %s" % ami_id   
else:
   print "Something Went Wrong!!" 
########################################Replication CODE################################
reservations = conn.get_all_instances(instance_ids=[sys.argv[1]])
instances = [i for r in reservations for i in r.instances]
for i in instances:
    key_name = i.key_name
    security_group = i.groups
    instance_type = i.instance_type
    subnet_name = i.subnet_id
    reserve = conn.run_instances(image_id=ami_id,key_name=key_name,subnet_id=subnet_name ,instance_type=instance_type,security_group_ids =security_group)
    print "new replica system id is " + reserve.instances[0].id

Actually the code before the REPLICATION CODE works fine and created a AMI .. after that i need to launch the instance, which throws an error:

Traceback (most recent call last):
  File "create_AMI_n_spin_instance.py", line 43, in <module>
    reserve = conn.run_instances(image_id=ami_id,key_name=key_name,subnet_id=subnet_name ,instance_type=instance_type,security_group_ids =security_group)
  File "/usr/local/lib/python2.7/dist-packages/boto/ec2/connection.py", line 973, in run_instances
    verb='POST')
  File "/usr/local/lib/python2.7/dist-packages/boto/connection.py", line 1208, in get_object
    raise self.ResponseError(response.status, response.reason, body)
boto.exception.EC2ResponseError: EC2ResponseError: 400 Bad Request
<?xml version="1.0" encoding="UTF-8"?>
<Response><Errors><Error><Code>InvalidParameterCombination</Code><Message>The parameter groupName cannot be used with the parameter subnet</Message></Error></Errors><RequestID>5242ae3a-03ea-491c-a230-5d86afcc3870</RequestID></Response>




Aucun commentaire:

Enregistrer un commentaire