A shortcut to accessing your hosts via SSH
Published in code on February 18th, 2023.
Does your activity revolve around connecting to multiple remote servers via SSH? You may end up having to type in the connection parameters quite often then.
There's a smoother way to access your hosts.
You might be accustomed to going usually for something like this, accompanied by the details for your authentication method:
ssh <user>@<host> -p <port>
This works quite easy when you're dealing with one or two servers, but can get complicated when you're involved in multiple projects, each of them perhaps with different environments and individual hosts that you may need to access from time to time.
The key (pun intended) would be to use a local SSH config file to bookmark your access into all servers.
Add your connections into a local config file
Create or edit your local SSH config
vi ~/.ssh/config
and add your connection details, based on the pattern below:
Host <bookmark_pattern>
HostName <host>
Port <port>
IdentityFile <path_to_your_key>
User <your_user>
You are free to customize the reference parameters:
<bookmark_pattern>is the way that is the most natural to you to remember the bookmark command. I usually prefer to go for<user>.<env>.<host><host>represents the remote server you're accessing<port>is optional and needs no further explanation<path_to_your_key>can be similar to ~/.ssh/id_rsa, depending on where & how you store your key
Connect to the host
This can be a wonderful solution in practice, especially when you're working with multiple servers, as the only thing you'd then need to remember is your <bookmark_pattern> and then run
ssh <bookmark_pattern>
You'll have to enter your passphrase for your private key and you're in.
Storing multiple hosts in your config
Having a clear & organised file will allow you to focus on your code over time and transform the ssh connection step into a trivial process. You may end up with a config file similar to this example.
# --- Start of MyApp ---
Host webuser.dev.myapp
HostName <host>
Port <port>
IdentityFile <path_to_your_key>
User <your_user>
Host webuser.stage.myapp
HostName <host>
Port <port>
IdentityFile <path_to_your_key>
User <your_user>
Host webuser.prod.myapp
HostName <host>
Port <port>
IdentityFile <path_to_your_key>
User <your_user>
# --- End of MyApp ---
Allow some whitespace in between your configured connections and do not forget the comments, to increase the legibility of the content. Multiply this by 3-5 projects and you'll easily be able to use such a pattern to access all the associated servers without any further effort.