Public key authentication for multiple private Github repositories

without using ssh-agent

  •  1 min  •  

Authenticating with Github using a single public key for all private repositories is straightforward enough: just follow Github's guide to authenticating with SSH and configure your ~/.ssh/config appropriately:

Host github.com
  Hostname github.com
  User git
  IdentityFile ~/.ssh/your_private_key

But things get more tricky if you don't want to use the same public key for all your private repositories, but instead want to use specific deploy keys for one or more of them. This can be done relatively easily by taking advantage of the Host field in ~/.ssh/config.

The trick here is to configure each Github repository to use a different hostname. Rather than github.com/username/repo_name, set it to repo_name.username, or repo_name.github.com, or something. What's important is that it doesn't clash with any existing domain you might want to access.

Set the hostname in your .git/config on each repository:

[remote "origin"]
  url = "ssh://git@repo_name1.username/alice/repo1.git"
[remote "origin"]
  url = "ssh://git@repo_name2.username/alice/repo1.git"

Then, in your ~/.ssh/config, map your made-up hostname to an actual host, with an actual identity file:

Host repo_name1.username
  HostName github.com
  User git
  IdentityFile ~/.ssh/your_1st_public_key

Host repo_name2.username
  HostName github.com
  User git
  IdentityFile ~/.ssh/your_2nd_public_key