Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create and download an AWS ec2 keypair using python boto

I'm having difficulty figuring out a way (if possible) to create a new AWS keypair with the Python Boto library and then download that keypair.

like image 219
Derek Avatar asked Jul 25 '12 21:07

Derek


People also ask

How do I create a Keypair on AWS?

To create a key pairOpen the Amazon EC2 console at https://console.aws.amazon.com/ec2/ . In the navigation pane, under Network & Security, choose Key Pairs. On the Key Pairs page, choose Create Key Pair. For Key pair name, type a name that is easy for you to remember, and then choose Create.

How do I add a Keypair to my EC2 instance?

To add or replace a key pairCreate a new key pair using the Amazon EC2 console or a third-party tool. Retrieve the public key from your new key pair. For more information, see Retrieve the public key material. Connect to your instance using your existing private key.


2 Answers

The Key object returned by the create_keypair method in boto has a "save" method. So, basically you can do something like this:

>>> import boto
>>> ec2 = boto.connect_ec2()
>>> key = ec2.create_key_pair('mynewkey')
>>> key.save('/path/to/keypair/dir')

If you want a more detailed example, check out https://github.com/garnaat/paws/blob/master/ec2_launch_instance.py.

Does that help? If not, provide some specifics about the problems you are encountering.

like image 68
garnaat Avatar answered Sep 19 '22 21:09

garnaat


Same for Boto3:

ec2 = boto3.resource('ec2')

keypair_name = 'my_key'


new_keypair = ec2.create_key_pair(KeyName=keypair_name)

with open('./my_key.pem', 'w') as file:
    file.write(new_keypair.key_material)

print(new_keypair.key_fingerprint)
like image 40
Michael A. Avatar answered Sep 21 '22 21:09

Michael A.