Multiple GitHub accounts
Challenge
If you work a lot with GitHub \ Bitbucket \ GitLab, at some point you’ll have several accounts.
Inevitably.
For example your personal one, and a company account to access private repos of the company.
Chances are you will still be using the same laptop to access all the repos.
So you’ll have a single global .gitconfig
, but you might want to differentiate your:
- SSH keys to access GitHub repos
git config user.email
that will become author email address of your git commits
Options
There are various ways of achieving this.
TMTOWTDI.
One popular way is to have aliases for github.com
defined in ~/.ssh/config
.
That will solve the SSH access problem, albeit with the custom URL in git remote.
But it won’t allow you to customize email or any other git parameter per GitHub Org.
Below is how I do it.
Tell me if the World moved on and there is a better way.
Approach is scalable, allowing you to have many accounts, not just 2.
Dir structure
Let’s assume we are using directory structure like this:
~/git/
github.com/
<account 1>/
<repo A>
<repo B>
<account 2>/
<repo X>
<repo Y>
...
gitlab.com/
...
bitbucket.org/
...
...
Adding new “account”
Repeat steps below for every additional account.
Let’s prepare some input:
export ACCOUNT_EMAIL_ADDRESS=...
export ACCOUNT_IDENTITY_FILE=~/.ssh/id_rsa_${ACCOUNT_EMAIL_ADDRESS}
SSH keys
You need to generate a separate SSH key for each distinctive GitHub account. This is because GitHub fails if SSH public key you are trying to add to your GitHub account, is already used in a different GitHub account. Error message you will see is:
Key is already in use
Generate new SSH key by:
ssh-keygen -t rsa -C $ACCOUNT_EMAIL_ADDRESS -P '' -f $ACCOUNT_IDENTITY_FILE
Go to your GitHub settings and add the content of the .pub
file.
git config
In all lines below use real values instead of:
- ACCOUNT_NAME
- ACCOUNT_EMAIL_ADDRESS
- ACCOUNT_IDENTITY_FILE
Add these lines to your ~/.gitconfig
:
[includeIf "gitdir:~/git/github.com/ACCOUNT_NAME/**"]
path = ~/git/github.com/ACCOUNT_NAME/.gitconfig
And add the custom config file itself ~/git/github.com/ACCOUNT_NAME/.gitconfig
containing:
[user]
name = ...
email = ACCOUNT_EMAIL_ADDRESS
[core]
sshCommand = "ssh -i ${ACCOUNT_IDENTITY_FILE} -F /dev/null"
Testing
git CLI
Tested successfully:
-
go to the repo dir and type
git config user.email
, you should see the value specific to the GitHub account. -
git clone ...
using SSH URL from the GitHub org to prove that custom SSH key is used
Atlassian SourceTree
Not tested yet.
Sumary
You mileage may vary.
May contain nuts.
Be your Karma improved if you automate the above.
Send me a PR.
Caveats
While git will work fine in this configuration, some other tools using git on the background may fail.
For example terraform init
or bundle install
trying to fetch dependencies from private git repositories will likely not recognize this custom git setup.