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?
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:
In the new versions of boto3 (I'm using 1.4.7) change this line:
keypair['KeyMaterial']
to
keypair.key_material
Add the feature to save to local keypair file
$ cat keypair.py
import boto3
keypair_name = "python_keypair"
ec2 = boto3.client('ec2')
keypair = ec2.create_key_pair(KeyName=keypair_name)
private_key_file=open(keypair_name,"w")
private_key_file.write(response['KeyMaterial'])
private_key_file.close
now you should get the private key locally
$ cat python_keypair.pem
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA14D9GAC7zVSRr3iHUyEaIF8ol5ccWBj9InVqYnF28l10EUCz
g5OLL5Ll6WiIYvlxhcRHM5d0os2Lg5SuKi0mTktYQ7QVD8RkdoEYIVrqgBir3VMf
8jG08JRhaJs4/OQk2+WAGecjcVx6joz9yXTRT3Maaec/4qNigfYMLpSsdAoZ0hrk
....
move it to ~/.ssh
and change permission to 600
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.