user1018513
user1018513

Reputation: 1682

Creating EC2 instances with key pairs in Boto2

I have the following code using boto.ec2 to connect to Amazon EC2 from python, but I'm struggling to deal with the .pem files. If I pass None to the run_instances call as the key name, I can create instances without any problem. However, if I pass any key name (whether or not I create it using the console, or manually as below), I systematically get the following error when I try to run an instance

EC2ResponseError: 400 Bad Request
<?xml version="1.0" encoding="UTF-8"?>
<Response><Errors><Error><Code>InvalidKeyPair.NotFound</Code><Message>The key pair 'newkey.pem' does not exist</Message></Error></Errors><RequestID>e4da5b1e-a8ec-42fb-b3ce-20aa883a0615</RequestID></Response>

When I check on the console for the appropriate region, the key is indeed created (it is also created in my home directory, but I still get the key does not exist error)

Any ideas?

Below is my current Python test code

 try:
    key_res = conn.get_all_key_pairs(keynames=[key])[0]
    print key_res
    print "Key pair found"
   except boto.exception.EC2ResponseError, e:
    print e
    if e.code == 'InvalidKeyPair.NotFound':
     print 'Creating keypair: %s' % key
     # Create an SSH key to use when logging into instances.
     key_aws = conn.create_key_pair(key)
     # AWS will store the public key but the private key is
     # generated and returned and needs to be stored locally.
     # The save method will also chmod the file to protect
     # your private key.
     key_aws.save(".")
    else:
      raise
    print "Creating instances"
    try: 
      conn.run_instances(ami[c.region.name], key_name=key,instance_type=instance,security_groups=[security_group])
    except Exception as e:
                print e
                print "Failed to create instance in " + c.region.name

Upvotes: 1

Views: 1255

Answers (1)

John Rotenstein
John Rotenstein

Reputation: 269111

This code (derived from yours) worked for me:

>>> import boto.ec2
>>> conn = boto.ec2.connect_to_region('ap-southeast-2')
>>> key_res = conn.get_all_key_pairs(keynames=['class'])[0]
>>> key_res
KeyPair:class
>>> key_res.name
u'class'
>>> conn.run_instances('ami-ced887ad', key_name=key_res.name, instance_type='t1.micro', security_group_ids=['sg-94cb39f6'])
Reservation:r-0755a9700e3886841

I then tried your key-creating code:

>>> key_aws = conn.create_key_pair('newkey')
>>> key_aws.save(".")
True
>>> conn.run_instances('ami-ced887ad', key_name=key_aws.name,instance_type='t1.micro',security_group_ids=['sg-93cb39f6'])
Reservation:r-07f831452bf869a14
>>> conn.run_instances('ami-ced887ad', key_name='newkey',instance_type='t1.micro',security_group_ids=['sg-93cb39f6'])
Reservation:r-0476ef041ed26a52f

It seems to work fine!

Upvotes: 1

Related Questions