Czar Pino

EST. 2017

How to simplify SSH access with SSH config

What originally started as me looking for a way to push code using different GitHub accounts led to one of my favorite self-discoveries: using SSH config to simplify SSH access to multiple servers. Unsurprisingly, this self-discovery is far from novel and has been employed by server admins long before I realized the inefficiency of my approach to SSH access.

The problem I’m trying to solve is basically the inefficiency of SSH with public key authentication. SSH commands with custom private keys can be quite lengthy and are unsuitable for manual input.

ssh -i /a/long/path/to/your/custom_id_rsa
ssh -i ~/.ssh/ec2_sg_id_rsa

SSH Config

Turns out it is possible to define hosts in your SSH config file along with the parameters you wish to use to connect to a host. This is especially useful for pushing code using different credentials as well as shortening the ssh command for logging into a remote server.

For a comparison, the ssh commands above can be reduced to the following:

ssh host-alias-a
ssh host-alias-b

*A pause here*

To achieve this, you simply have to add a couple lines of code to your SSH config. This file is typically inside the .ssh folder in your home directory.

# ~/.ssh/config

Host host-alias-a  
    User a-long-username  
    IdentityFile /a/long/path/to/your/custom_id_rsa

Host host-alias-b  
    User pino-ec2-user  
    IdentityFile ~/.ssh/ec2_sg_id_rsa

As you can see, all relevant information are specified inside the host definition: the hostname, user, and the identity file or private key to be used for authentication. All that’s left is identifying which host you want to log into when invoking the SSH command. Even if you had multiple servers or multiple credentials for the same servers, your developer experience will be much less cumbersome with SSH config.

Finally, there are also other ways to achieve what SSH config does here such as aliasing or good old copy-paste (and variants). However, I find this approach preferable as it seems to be a natural solution resulting from SSH’s design and the resulting dev experience isn’t really that much different.

Published by Czar Pino on Saturday May 5, 2018

Permalink - Tags: programming, server-administration, devops, ssh

« How to tell Git which SSH Key to use