Multiple Git accounts with different SSH keys
It's quite simple to setup multiple Git (in this case GitHub) accounts on the same machine, each using different SSH keys. The scenario that I use this for is to have both a personal account and a work account.
Host github-personal
HostName github.com
IdentityFile ~/.ssh/personal_github_key
Host github-work
HostName github.com
IdentityFile ~/.ssh/work_github_key
You also need to set your remotes to use the above Host.
When you clone you need to change this:
git clone git@github.com:personal-org/repo.git
to this:
git clone git@github-personal:personal-org/repo.git
If you already have a repo you can change the remote addresses.
// see what is currently set
git remote -v
git remote set-url origin git@github-personal:personal-org/repo.git
Different Emails for GitHub
Something else that you may run into is GitHub showing the wrong user in the commit history. This was happening for me because of the email address used in .gitconfig
You may have set this using:
git config --global user.email "some@email.com"
GitHub uses this email to tie a commit to a GitHub account. This caught me by surprise as I thought it would match based on the ssh key used.
In order to fix this we can add some conditionals to our .gitconfig
This sets up a default configuration and tells git to load .gitconfig-work if your current path includes "company-projects/"
New commits should now be shown as the correct user.