Dušan Simić

ssh vol 1. - Git server SSH key configuration

The authentication issue

Now that most major Git servers (namely GitHub and GitLab) have switched to required ssh configuration, users need to create ssh keys and add them to their profile in order to push or pull anything to and from the servers.

This is not really a problem until users start to have a lot of keys in ther .ssh directory. That is an issue because ssh actually, if the ssh key is not explicitly specifed, just starts trying all the ssh keys from the .ssh directory. The Git servers will after a few failed attempts just close the connection and users can’t do anything because of that.

It’s fairly easy to handle this so I’ll just suggest a solution but I’ll also introduice another potential issue and a solution for it later in the post.

Configure the key

SSH uses a special file to allow users to configure connections and connection parameters so they could save time when they connect a lot to some server. Since git essentially uses ssh to authenticate on the servers, the ssh config file is used by git.

The config file is located at ~/.ssh/config. The following example of the config file contents configures the GitHub server to use a specific key from the .ssh directory.

Host github.com
  IdentityFile ~/.ssh/github

This is basically all you need to do. This way, when you run git clone or any other git command which communicates with the server, git will automatically pick up the specified key instead of trying all the keys from .ssh

The multiple account issue

Let’s say you have two accounts on GitHub, one personal and one used for work. In that case you need two ssh keys but here’s the problem, it seems that you can only specify one key per server.

Host and HostName

Well, that’s not exactly true. The Host option in the ssh config file actually specified what you type when connecting to a server. For example when you want to clone a repository from GitHub, you would type git clone git@github.com:.... That Host option then gets matched to your github.com server in the git clone command. Here’s where the HostName property comes into play. We can set some other value we want for Host but the HostName is actually the server that the host resolves to.

In the following example we’re setting two Host configurations, one for personal and one for work account.

Host github.personal
  HostName github.com
  IdentityFile ~/.ssh/github.personal

Host github.work
  HostName github.com
  IdentityFile ~/.ssh/github.work

Here we’re referencing two different keys but also for differnet hosts. They both connect to github.com but with differnet keys. When cloning repositories, we’ll need to specify the host we’ve defined instead of github.com, like so.

# cloning from personal account
git clone git@github.personal:...
# cloning from work account
git clone git@github.work:...

It’s a simple configuration which will save you from a lot of headaches.