Multiple Github and SSH accounts
Hey!
Have you ever needed two different GitHub accounts — one for personal use and one for work? GitHub doesn’t allow the same SSH key to be used for multiple accounts; if you try to reuse it, you’ll see a “Key Already in Use” error.
So, what’s the best way to set this up on your computer?
First, you’ll need to create two separate SSH keys and add them to your GitHub accounts. I usually use this to generate them:
cd ~/.ssh
ssh-keygen -t ed25519 -C "your-email@company.com" -f company
ssh-keygen -t ed25519 -C "your-email@personal.com" -f personal
Now you have 4 different files at ~/.ssh
. company
and personal
are your private keys. company.pub
and personal.pub
are the public keys you're going to add to Github.
Time to adjust your git config to use the proper keys in each repo. I usually have a folder workspace with all my projects, like the following structure:
.workspace
├── personal
└── company
Define your .ssh/config
in the following way:
Host github-company
HostName github.com
AddKeysToAgent yes
IdentityFile ~/.ssh/company
Host github.com
HostName github.com
AddKeysToAgent yes
IdentityFile ~/.ssh/personal
The last step is to configure your .gitconfig
:
[user]
# Personal configuration as default
name = Your Name
email = your-email@personal.com
[includeIf "gitdir:~/workspace/company"]
path = ~/.dotfiles/src/gitconfig/work
And on ~/.dotfiles/src/gitconfig/work
:
[user]
name = Your Name
email = your-name@company.com
Now, if you want to clone a project at ~/workspace/company, you need to use the following command:
git clone git@github-company:org/repo.git
Notice the host name will be different, that's what makes the connection between git and the work's SSH key. If you try to push or pull, the SSH key will be automatically be used. Check that with git remote -v
:
origin git@github-company:org/repo.git (fetch)
origin git@github-company:org/repo.git (push)
That's it! Feel free to comment if you have a better approach :)
Subscribe to my newsletter
Read articles from Diógenes Fernandes directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Diógenes Fernandes
Diógenes Fernandes
I'm from Brazil and I've been working professionally with technology since 2009. I love to learn and my current professional interests are: Infrastructure Security Platforms Cloud Coding and automation (always my number #1 <3)