'AWS CLI: Key is not in valid OpenSSH public key format

How to solve this?

# I used this command to create the key with a password
$ ssh-keygen -b 2048 -t rsa -C "awsfrankfurt" -f ~/.ssh/awsfrankfurt

# Then when I try to import it into AWS EC2, the error appears:
$ aws --region eu-central-1 ec2 import-key-pair \
    --key-name "awsfrankfurt" \
    --public-key-material ~/.ssh/awsfrankfurt

An error occurred (InvalidKey.Format) when the ImportKeyPair operation: 
Key is not in valid OpenSSH public key format


Solution 1:[1]

Create your key and then when calling aws's --public-key-material argument, call it with file:// in front of your key path.

Example:

$ aws --region eu-central-1 ec2 import-key-pair \
    --key-name "awsfrankfurt" \
    --public-key-material file://~/.ssh/awsfrankfurt  # <-- this

This is a weird issue, because, file:// prefix is usually used for Windows, but, here with aws, it applies to unix based terminals as well.

Solution 2:[2]

AWS only supports RSA keypairs, it does not support DSA, ECDSA or Ed25519 keypairs. If you try to upload a non RSA public key you will get this error.

This is documented here:

Amazon EC2 does not accept DSA keys. Make sure your key generator is set up to create RSA keys.

The error message is misleading as you can upload a valid non RSA key and get the error:

Error import KeyPair: InvalidKey.Format: Key is not in valid OpenSSH public key format

This answer should be useful for people who find this page after searching for this error message.

Solution 3:[3]

I ran into the same situation when I was creating an aws keypair using pulumi. Strangely, it worked when I used the content of the public key rather than the .pub file.

So here is what I changed in my code.

from :

aws.ec2.KeyPair("keypair", public_key="~/.ssh/mykey.pub")

to:

aws.ec2.KeyPair("keypair", public_key="ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC9u37J5tfzmeA8INBCcFSPKnUN8GIjYFdPOOCn8AjUC5iTJX/7TWd3pZ42Z++RCIlvBvKkH7LL1p"

Changed from path to .pub file to the content of .pub file

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Inanc Gumus
Solution 2 htaccess
Solution 3 Tapan Hegde