How many times did you forget where is your key to login to AWS EC2 instance? How many times did you have to search in Slack or in your email history to get the IP address you needed to access client's remote server?

Tired of using ssh like this?

ssh -i ~/Downloads/example-dev-key.pem ubuntu@example.com

No more!

You need to learn how to properly use config file for SSH. You can specify all the necessary details once and then just forget it. And let's be honest, we will forget it.

Only one thing is required: you need to have your private key, as the config does not support password authentication.

First we need to create our config file and set correct permissions.

touch ~/.ssh/config
chmod 600 ~/.ssh/config

We will be editing this file from now on.

How to configure access to AWS EC2 instance

First of all, you should copy your key somewhere safe, I have decided to copy it to my .ssh folder so I can keep everything together as it makes it easier for me.

Example config entry:

host ec2-example-dev
 Hostname example.com
 Port 22
 IdentityFile ~/.ssh/example-dev.pem
 User ubuntu

Lets break it down:

  • host: this is the name you choose for your server. You will use it to ssh to it.
  • Hostname: this is the hostname or IP address of the server
  • Port: port where the SSH server is running, defaults to 22
  • IdentityFile: this is why we are doing this, it allows us to specify key for our ssh connection
  • User: name of the user which will be connection to the server

To connect to our server, we simply call ssh like this:

ssh ec2-example-dev

Isn't it easier? Easy to remember. Now I just have to make sure I don't forget how I named my servers 😅.

How to configure access to servers with your key

If you are using your regular ssh key (id_rsa) to access servers, you can make use of this configuration as well. You can set up custom names for different servers, set up ports and usernames for them.

How I ssh'd before:

ssh martin@example.com

or if you are using custom port (which you should be using):

ssh martin@example.com -p 2233

We can simplify it with our config like this:

host example
 Hostname example.com
 Port 2233
 User martin

And we can ssh

ssh example

This shows the power of config file for SSH. It really helped me to manage all the servers I need to access on regular basis and honestly, EC2 instances with custom keys were the biggest pain to access, but now with well defined config file, it is a breeze to connect to them to manage and monitor them.

Learn more how to use ssh config files here.

M.