SSH and Multiple Github Accounts
Overview
Enable the use of multiple ssh-keys (for multiple accounts) in a non intrusive manner. It relies on / uses the following concepts:
- Using
insteadOf
in .gitconfig (Ref) - Using an ssh config file (Ref
- 1Password 8 (Ref) (ssh-agent can be used instead)
- Specify exact key in ssh-agent (1password) to be used (Ref)
- General guidance on using multiple ssh keys (Ref)
How this guide is different
The general suggestions found via searching google requires the developer to change the “hostname” when they do a clone. This is a manual step that takes away the ease of clicking on the Github code/clone “copy” button.
With the setup as described here, the normal flow remains unchanged.
Example
Assume we want to configure 2 ssh keys for 2 different github accounts.
- Github account 1 (
acc1
) with ssh keyacc1-ssh
- Github account 2 (
acc2
) with ssh keyacc2-ssh
Steps
Setup SSH keys
Setup your SSH keys in github and ssh-agent (1password) as you’d normally do
Make public keys available
- Store
acc1-ssh.pub
in$HOME/.ssh/acc1-ssh.pub
- Store
acc2-ssh.pub
in$HOME/.ssh/acc2-ssh.pub
Update .ssh/config
Add the following to your $HOME/.ssh/config
Host acc1-github.com
Hostname github.com
IdentityFile ~/.ssh/acc1-ssh.pub
Host acc2-github.com
Hostname github.com
IdentityFile ~/.ssh/acc2-ssh.pub
This will cause the ssh client to use different ssh private keys (via ssh-agent) for the different domains. Setting the IdentityFile to the public key, tells ssh-agent which private key to use.
This is where the normal guidance for using multiple keys end. However, this requires the developer to change the url when cloning. I.e. instead of
git clone git@github.com:acc1/repo
the developer has to change the url and clone with the new url
git clone git@acc1-github.com:acc1/repo
Update $HOME/.gitconfig
Add the following to your $HOME/.gitconfig
[url "git@acc1-github.com:acc1"]
insteadOf = git@github.com:acc1
[url "git@acc2-github.com:acc1"]
insteadOf = git@github.com:acc2
This tells the git client to use git@acc1-github.com:acc1
instead of git@github.com:acc1
, which in turn tells the ssh client to use the key associated with acc1-github.com.
The end result is that the developer can clone via
git clone git@github.com:acc1/repo
and the git remote will be setup as
origin git@acc1-github.com:acc1/repo.git