When you create a new instance in EC2, you will receive a PEM file which acts as the access key. You will need to use it for SSH on the server, so you will need to add it to your keychain for easy access.
How to use your PEM file
You can use PEM files manually by adding the -i flag to ssh:
ssh -i keyfile.pem user @ host
It’s hard to type every time, so there are several ways to fix this.
The simplest method would be to add your own public keys to your EC2 instance and ignore the PEM file for all future connections. Your public key is usually stored in ~ / .ssh / id_rsa.pub, so you will want to copy it to the ~ / .ssh / authorized_keys file on the server. If you’re a one-man team and don’t worry about doing it every time, that’s all you have to do.
However, you will need to follow this process each time you create a new instance. But with PEM files, you can reuse them between instances. In addition, they are independent of your personal private keys, so you can give them to other people who need ssh access.
The ssh-add command will store a key in ssh-agent until you log out:
ssh-add ~ / keyfile.pem
However, you will need to run it every time you restart, so it’s not ideal. You can add it to your ~ / .bashrc or ~ / .bash_profile to run it each time the terminal starts, which resolves the problem. Make sure to redirect the output to / dev / null to disable the command, or you’ll see “Identity added” each time you open the terminal.
ssh-add ~ / keyfile.pem> / dev / null 2> & 1
Store SSH keys in macOS keychain
If you are using macOS, you can store additional SSH keys in the macOS keychain. Open ~ / .ssh / config and add the following lines:
You can now add keys with
ssh-add -K ~ / keyfile.pem
The keys will be stored in the keychain and will persist during restarts. They will be automatically loaded as ~ / id_rsa.
Replace id_rsa with your new key
While this option works, it is not really something that we recommend. But, if for some reason you really want your AWS private key to be your new personal private key, you can replace id_rsa with the AWS PEM file. id_rsa is loaded by default, so you will use this default key for everything.
Make absolutely sure that you don’t use your current private key for anything (SSH to other servers, GitHub, etc.). Even if you think not, you must back up your current SSH keys before continuing:
mv ~ / .ssh / id_rsa ~ / .ssh / id_rsa_old
mv ~ / .ssh / id_rsa.pub ~ / .ssh / id_rsa_old.pub
The AWS PEM file must be converted to PKCS8 format to be used as a private key. You can do this with OpenSSL:
openssl pkey keyfile.pkcs8
Then you will need to generate the corresponding public key, still using OpenSSL
openssl rsa -in keyfile.pkcs8 -pubout> keyfile.pub
Then, making sure you have saved your old id_rsa, you can replace them with the new ones:
mv keyfile.pkcs8 ~ / .ssh / id_rsa
mv keyfile.pub ~ / .ssh / id_rsa.pub