Back to list
Multi account SSH GIT access
Published
In git cli 
Long

Everything is setup: your github account is created, you added an SSH public key to be able to access your projects with SSH. You start using this setup for your side projects as it is very convenient.

Then comes your new employer, who requires you to create another account on the very same platform and add another SSH private key. The problem is that SSH sees no differences between the 2 accounts; it sees a host and a user and tries all your keys in sequence so most probably only one is used and fails when you want to access the other one.

How do you tell SSH to be more wise in choosing the correct key?

Multi account SSH GIT access

Let see the options.

The pragmatic approach

Use the same SSH key for both... Okay, let's say we can't do that.

You can also argue that you could use the same account for both situations. But it might not be accepted.

The easy to find approach

If you search a little bit, you'll get the following trick: change the host name for one of the setups and add some configuration to SSH. You end up with a clone string like :

git clone git@work_github/work_magnus/my-project.git

and the .ssh/config contains:

Host github.com
IdentityFile ~/.ssh/my-private-key

Host work_github
HostName github.com
IdentityFile ~/.ssh/my-work-key

This is nice and very widespread solution. I don't like that everytime I need to clone a project, I need to think about it.

There is a another solution that does not imply to change the paths nor change the ssh configuration.

Enters the GIT_SSH_COMMAND environment variable

Since git version 2.10 (not sure), git provide a way to configure SSH through the GIT_SSH_COMMAND environment variable.

I put all work related repositories in a folder called Work and I define the variable based on whether Work is in the current path (pwd). In my .bashrc

function switch_git {
if [[ "$(pwd)" = ~ "/Work/" ]]; then
export GIT_SSH_COMMAND="ssh -i ~/.ssh/my-work-key"
git config --global user.name "Magnus Anderssen"
git config --global user.email "magnus@work.test"

else
export GIT_SSH_COMMAND="ssh -i ~/.ssh/my-private-key"
git config --global user.name "Magnus Anderssen"
git config --global user.email "magnus@home.test"
fi
}

function cd {
if [ -z "$1" ]; then
command cd "$HOME"
else
command cd "$1"
switch_git
fi
}

switch_git

It configures correctly what key ssh is supposed to use with git when the terminal is created but also when changing directory (cd).

The git config are not required but might avoid some personal account commiter appearing in the work git log or the opposite.

Disclaimer: I only use the git CLI to clone, fetch and push.

When searching for references, I also found that you can do the exact same thing by defining the core.sshCommand configuration option of git.

References: