How to use multiple ssh-keys with multiple GitHub accounts

Posted by on 1 March 2020

For various reasons I have more than one GitHub account. Unfortunately GitHub only allows you to use your ssh-key on a single account. So if you have multiple accounts like I do then you need multiple ssh-keys and it can be annoying to deal with unless you get a little creative with your ssh configuration. Here is what I did for years before I finally got annoyed enough to research a better way.

  1. Change to project directory, do some work
  2. git push
  3. Get error about not having access rights
  4. ssh-add ~/.ssh/id_rsa_whatever_key
  5. On rare occasions I might still get the error because I had another key loaded that hadn't expired yet
  6. ssh-add -D (to remove all keys)
  7. ssh-add ~/.ssh/id_rsa_whatever_key
  8. git push (finally it works!)

The other thing that I would have liked to do is maybe even use my git package from inside my editor, Emacs, to push and pull commits but figuring out how to get that to work with various keys never seemed to make it on my radar. It's amazing how much you can put up with while you're in the middle of something and you just want to get it done. But one day I had finally had enough and I had some extra time so I decided to research how others have solved the problem and came up with a solution. I thought git might have a configuration where you could set a path to a key to be used for each repository, kind of like you can with your email address if you want to use a different one for different repositories for some reason. You can set repository level configurations. But it turns out this is all handled at the ssh level. The solution is quite simple. I have 3 ssh keys, so here is what I did.

  1. Create 3 ssh-keys giving each one a unique name, (ssh-keygen -t rsa)
  2. Create 3 github.com entries in your ~/.ssh/config file, one for each key you created
    Host github.com-key1
        HostName github.com
        User git
        IdentityFile ~/.ssh/id_rsa_key1
    Host github.com-key2
        HostName github.com
        User git
        IdentityFile ~/.ssh/id_rsa_key2
    Host github.com-key1
        HostName github.com
        User git
        IdentityFile ~/.ssh/id_rsa_key2
    
  3. Visit the repo or repos you want to use the first key with and update the remote with the new ssh config entry
    git remote set-url origin git@github.com-key1:path-to/repo.git
    
  4. Rinse and repeat for your other repos using the appropriate key

Now that you have your keys in place, git push/pull will just work without any key management whatsoever! You never have to worry about them expiring, overlapping, or any of those things you might have had to deal with before if you were hard-headed like me. It will also just work with Magit or whatever editor plugin you might want to use in your environment.

Tags: #git

Categories: #technology

Tags

Categories