Non-standard SSH key storage

2 minute read

If you use one computer for multiple purposes (e.g. work and personal) you might find yourself wanting to separate your SSH keys into separate folders. In my case I have a 'personal_keys' folder that sits inside the default one:

~/.ssh/personal_keys

Unfortunately a simple SSH command won't look for your keys in anything other than the top-level directory, and you really don't want the bother of having to specify the key's location every time. However, there is a solution — your ~/.ssh/config file.

This file normally just points to the default ~/.ssh/id_rsa key, but we can add additional hosts at the top of the file which point to our alternative key directory:

Host gitlab.com
Hostname gitlab.com
IdentityFile ~/.ssh/personal_keys

Host joshuahughes.co.uk
Hostname joshuahughes.co.uk
IdentityFile ~/.ssh/personal_keys

Host *
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/id_rsa

With these additions, now when I run an SSH command for either gitlab.com or joshuahughes.co.uk my personal keys will be referenced:

ssh my_cpanel_username@joshuahughes.co.uk

A connection to any other host will skip through to the Host * block at the end of the file and reference the standard key location. Simples!