The purpose of this article is to demonstrate how to add an ssh key to an existing ec2 instance. If you are reading this then you have likely created an ec2 instance but cannot access it remotely except through the AWS console. It’s important to always have a way to ssh into your ec2 instances external from the AWS console. Make sure to secure the instance with security groups.
To create a key pair using Amazon EC2 you can follow the instructions here: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/create-key-pairs.html#having-ec2-create-your-key-pair
Alternatively you may create a key pair on the command line. We have written a previous article detailing how to generate your own key pair here with the ssh-keygen command.
After creating your key pair you will need to extract the public key from the private key if you do not already have it in a separate file. To extract the ssh public key from it’s corresponding private key run the following command.
ssh-keygen -y -f ~/.ssh/id_rsa > ~/.ssh/id_rsa.pub
-y -f will read the private SSH key file and generate the public key from it before outputting it to the specified public key file.
Next you will have to copy the new public key to your EC2 instance by first connecting to it through the AWS console. Paste the public key into the
.ssh/authorized_keys file. Note that through your browser you much use
CTRL v to paste the public key as right clicking to paste will not work.
Next, reload the sshd process with the following command:
systemctl reload sshd
You should now be able to ssh into the ec2 instance from the command line.
Conclusion – ssh ec2 instance
This article has demonstrated how to add an ssh key to an existing ec2 instance and then how to ssh into the ec2 instance from the command line with the new ssh key. Let us know in the comments if you have any questions or would like to see more examples of how to ssh into an ec2 instance.
Leave a Reply