Posted on Leave a comment

Using multiple SSH Keypairs for Git

Git Logo

When using multiple (GIT) services and repositories from different provider you are very likely to also use different sets of SSH keypairs. At first managing multiple keypairs might sound a little complicated but it is in fact quite easy.

Let’s say you have three keypairs for three different GIT services:

  • GitHub
  • PHP Cloud
  • your local GIT server

In order to separate access to these services you are using different keypairs for each service. In order to tell GIT to automatically choose the right keypair for the service you are trying to access you need to edit your local SSH config file (.ssh/config), as well as the GIT repository’s config file (.git/config).

First, you need to create an alias for each service in your SSH config file:

Host phpcloud-mycontainer
  User mycontainer
  IdentityFile ~/.ssh/id_rsa.phpcloud-mycontainer

Host github-myaccount
  User myaccount
  IdentityFile ~/.ssh/id_rsa_github-myaccount

Host localgitserver-myaccount
  HostName localgitserver.local
  User myaccount
  IdentityFile ~/.ssh/id_rsa.localgitserver-myaccount

As you can see three aliases have been specified for the three services. This provides you with the option to specify what key to use depending on the service.

In order to “activate” these alias for existing repository clones you need to edit .git/config to set the proper remote origin. So for instance your config for GitHub would look something like the following:

[remote "origin"]
  url = ssh://git@github-myaccount:myaccount/myrepo.git

Now all you need to do is the use the alias when accessing your services. This way the proper SSH key will be determined.

Also note that this approach is not limited to GIT – you are able to use these simple steps for any service based on SSH.