2019-05-11
How to work with multiple git repository servers, and users, from a single machine.
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:
git config user.email that will become author email address of your git commitsThere 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.
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/
...
...
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}
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.
In all lines below use real values instead of:
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"
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
Not tested yet.
You mileage may vary.
May contain nuts.
Be your Karma improved if you automate the above.
Send me a PR.
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.