If you want a smooth ride on the cloud paradise you should leave your keys in the secret stash! Well, jokes aside, it seems we will be coming back and forth to our EC2 instances and, following good examples from @atgmello and @gabfr, I've come up with a simple step-by-step procedure to easy the journey whenever we want to rapidly connect to our instances.
After you set up your permissions with:
chmod 400 <your-pem-path>
And connect for the first time with:
ssh -i <your-pem-path> <your-instance-user-and-url>
You can set up an alias on your local machine to connect with this instance. Simply run,
vim ~/.ssh/config
And all you need to do is set up some keys like the following structure:
Host <whatever-name-you-want>
Hostname <your-ec2-url-without-everything-before-the-@>
User <everything-before-the-@>
Example
Host ds4a
Hostname ec2-18-211-67-53.us-east-2.compute.amazonaws.com
User ec2-user
Ok, so what now? First, let's copy your ssh id_rsa.pub content and keep it for a while. To do that, simple go:
cat ~/.ssh/id_rsa.pub
And copy the contents, which may look like the following:
ssh-rsa AAAAB3NzaC1yc2EAAAAABAQC8++Uy4hHHGQVdbutRQnIcDV/FsW9apHz8Ard1JmVtNbve
VDkU6+PCDlwFQXXPu27wFg4tjcYo72A6echXHIXV4exzXBHjxX2JKk/95P/uFoCUohj12GVtKBhes
Q4r50ZbVpB16n5iNqPN3FMWC6lCsHhldOblVyabK9R1hvlE99a9Bvk1e/enniQoyNFhAOYxMdXfTF
Y90LNUQiYFmlX8aHhe0LrCbm6AndgyXrc/ZDD7446/9peKT/ALPeOnNJ3k5bK8k5WQ1S2BMyZpt1h
RWzt3maIxy3r0+s66emctT317+gxk0WiE3kn <your-user>
You don't have one? Shame! But no trouble whatsoever, this resource has everything you need to know.
Now log in your machine with the next line:
ssh -i <your-pem-path> ds4a
Notice that ds4a is the alias I have for this machine!
Now, we have to add our id_rsa.pub key to our EC2 machine, in order to skip adding our pem path every time we log in. On your EC2 instance, type:
sudo vim ~/.ssh/authorized_keys
A text file should open up. PLEASE BY ALL THAT IS GOOD AND PRECIOUS ON THIS EARTH
Without it your instance is as good as dead, you will never be able to log in it again!
Just add the copied contents to your authorized keys file, save it...
ssh ds4a
and - voi-la!
Last login: Fri Mar 13 23:17:38 2020 from 191.161.191.24
__| __|_ )
_| ( / Amazon Linux 2 AMI
___|\___|___|
https://aws.amazon.com/amazon-linux-2/
No packages needed for security; 6 packages available
Run "sudo yum update" to apply all updates.
[ec2-user@ip-133-41-38-124 ~]$