SSH

SSH #

Using multiple SSH keys and accounts with GitHub #

I tried adding the same SSH key for my two different GitHub accounts, which to my surprise, is not possible. If you do this you get a Key already in use error, even though the SSH key is connected to another account than the one you are currently logged in. So apparently GitHub associates every SSH key with a unique account. This requires us to use two different keys on the same machine.

First, generate two SSH keys (using the ed25519 algorithm here) in your ~/.ssh/ directory.

ssh-keygen -t ed25519 -C "your_email@example.com"
ssh-keygen -t ed25519 -t secondary -C "your_email@example.com"

After doing this two public and two private SSH keys must exist under ~/.ssh/, assuming you renamed the first one to primary. Use ls -l to list the contents of the directory.

ls -l
primary
primary.pub
secondary
secondary.pub

Then, we need to configure the config file. Open it using a text editor (e.g. ~/.ssh/config)` and add the following contents:

Host github.com
    Hostname github.com
    User git
    IdentityFile ~/.ssh/primary
    IdentitiesOnly yes

Host github.com-secondary
    Hostname github.com
    User git
    IdentityFile ~/.ssh/secondary
    IdentitiesOnly yes
  • Host is a friendly name that you want to substitute in URLs.
  • Hostname is the actual host name.
  • User is the username before the @ symbol in git@github.com:foo/bar.git.
    • By adding the User git directive in the config file, we can omit the explicit username in our connection strings, like git clone github.com:foo/bar.git.
  • IdentityFile is the absolute path to the private key.
    • Since it is not a relative path, using ./personal or personal will not work.
  • IdentitiesOnly prevents the ssh-agent from trying other SSH keys (if they exist) for connection and forces only the identity files we have provided in this config to be used.
    • However, I tried adding multiple IdentityFile directives to config, which did not work and failed to authenticate for both my accounts. I assume this is used for the ssh command and fails for git. Having multiple IdentityFiless in a single Host configuration causes git to fail.

After saving this file, we need to substitute the github.com domain name by github.com-secondary in every URL where we want the secondary SSH key to be used. For example, git@github.com:foo/bar.gitgit@github.com-secondary:foo/bar.git.

If you are using scripts provided to you for updating your project and git settings, you either need to do this substitution everyhwere without knowing what kind of problems that is going to cause (horrible), or simply comment out the other SSH key and use the correct one with github.com domain.

So far, I could not find a way of doing this without changing the domain name.