Friday, February 4, 2022

[SOLVED] Create new EC2 keypair on AWS with Boto3

Issue

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?


Solution

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:



Answered By - John Rotenstein
Answer Checked By - Mary Flores (WPSolving Volunteer)