Multiple SSH Keys for Multiple Mercurial Repositories

Authored by Sean Johnson

Overview

With the prevalence of resources such as BitBucket, and hg-gateway, it sometimes transpires that users will have multiple ssh key pairs for use with different Hg provides a native solution.
While tested explicitly on OS X, the command line instructions should also work on sufficiently UNIX like systems, such as Linux or BSD distributions.

SSH Config

The system wide ssh configuration can be overridden on a per user basis by creating a ~/.ssh/config file. Details on what options are available for that file are available in the ssh_config(5) man page. In this particular case, we are going to focus on the options necessary to differentiate Hg repositories based on unique ssh keys.
For this example, there will be three Hg repositories in play, with two being from the same source, using the same user but with different ssh keys, and the third being accessed via an alternate port.
In all cases, the required components are Host, HostName, User and IdentityFile. For the first repository, there will also be an alternate port.

Example 1

~/.ssh/config
  Host repo1
    HostName host1.example.com
    Port 2222
    User user1
    IdentityFile ~/.ssh/id_rsa.user1

Be sure that the IdentityFile is the appropriate private key for the user account, and the corresponding public key has been added to the remote side authorized_keys file.
In the event that different keys are being used for different repositories at the same location, the following configuration can be used:

Example 2

~/.ssh/config
  Host repo2
    HostName host2.example.com
    User hg
    IdentityFile ~/.ssh/id_rsa.hg_repo2

Example 3

~/.ssh/config
  Host repo3
    HostName host2.example.com
    User hg
    IdentityFile ~/.ssh/id_rsa.hg_repo3

Using the config with Mercurial (command line)

When cloning a Hg repository using ssh and the specific keys is now as simple as specifying the Host named in the ~/.ssh/config file. THe following clone commands correspond to their respective ssh examples detailed in the previous section.

Example 1

hg clone ssh://repo1/repo_name repo_name

Example 2

hg clone ssh://repo2/repo_name repo_name

Example 3

hg clone ssh://repo3/repo_name repo_name

Using the config with MacHg

The process is practically identical. When cloning a repository, enter the appropriate ssh://repo/repo_name component in the Server URL: field.