Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create new EC2 keypair on AWS with Boto3

The boto3 1.1.2 docs say that the create_key_pair command is supposed to return a dict containing the private key of the newly created keypair.

I am indeed using that version…

>>> import boto3
>>> boto3.__version__
'1.1.2'

…yet when I run create_key_pair I am instead returned a KeyPair object which does not appear to contain any information about the private key. The keypair does get created, it's just that I have no way of retrieving the private key because it is only ever available at the time of the keypair's creation. Older boto APIs apparently had a .save method on the KeyPair object to save the key to a file, but that too appears to have been removed from the API.

In boto3 1.1.2, how does one create a new EC2 keypair and retrieve its private key?

like image 820
ESultanik Avatar asked Aug 26 '15 18:08

ESultanik


1 Answers

The private key is available in keypair['KeyMaterial']:

>>> import boto3
>>> ec2 = boto3.client('ec2')
>>> keypair = ec2.create_key_pair(KeyName='foo')
>>> keypair['KeyMaterial']
'-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCA...\n-----END RSA PRIVATE KEY-----'

References:

  • boto3 create_key_pair() documentation
  • boto3 EC2 migration guide
like image 68
John Rotenstein Avatar answered Sep 22 '22 14:09

John Rotenstein