Multiple Github accounts & SSH keys on the same machine

If like me you have 2 or more, different Github accounts on the go, then accessing and committing as both on the same machine can be a challenge.
In my case, I have 2 accounts, one for work associated with my company email and a second for my own personal code.

If you'd like to be able to checkout, code and commit against different repo's across different github accounts on the same machine, then you can do so by setting up multiple ssh keys, and having hostname aliases configured in your .ssh config file.

First off all, you'll need to generate your SSH Keys. If you haven't done this already, you can use the following commands to generate your keys.

$ ssh-keygen -t rsa -C "eoin@work.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/c/Users/eoin/.ssh/id_rsa): id_rsa_eoin_at_work

$ ssh-keygen -t rsa -C "eoin@home.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/c/Users/eoin/.ssh/id_rsa): id_rsa_eoin_at_home

Once you've created your 2 files, you'll see 2 key pair files (the file you specified and a .pub) in your ~/.ssh directory. You can go ahead and add the respective key files each of your Github accounts. It's in the Github > Settings < SSH and GPG Keys section of your settings. You'll also need to add these files to ssh.

Next you'll want to create an ssh config file in your ~/.ssh directory. You can see mine below.

Host github.com
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa_eoin_at_work

Host personal.github.com
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa_eoin_at_home

Here's the trick, when you execute a git clone command to clone a repo, the host in that command is not a real DNS hostname. It is the host entry specified on the first line of each section in the above files. So you can very easily change that. Now, if I want to check out work related projects from my work account, I can use.

git clone git@github.com:eoincgreenfinch/heartbeat.git

# don't forget to set your git config to use your work meta data.
git config user.name "eoincgreenfinch"
git config user.email "eoin@work.com" 

But if I want to check out code from my personal account, I can easily modify the clone URI with the following.

git clone git@personal.github.com:eoincampbell/combinatorics.git

# don't forget to set your git config to use your work meta data.
git config user.name "eoincampbell"
git config user.email "eoin@home.com" 

~Eoin Campbell

Eoin Campbell

Eoin Campbell
Dad, Husband, Coder, Architect, Nerd, Runner, Photographer, Gamer. I work primarily on the Microsoft .NET & Azure Stack for ChannelSight

CPU Spikes in Azure App Services

Working with Azure App Services and plans which have different CPU utilization profiles Continue reading

Building BuyIrish.com

Published on November 05, 2020

Data Partitioning Strategy in Cosmos DB

Published on June 05, 2018