2 Git Multi SSH
tengel edited this page 2024-09-05 08:27:27 -05:00

git multiple accounts same host

git client 2.10.0 or newer required

problem

scenario:

  1. two (or more) git accounts at the same host
    • git@gitlab.com/user1
    • git@gitlab.com/user2
  2. using unique SSH keys with each git account
    • host uses SSH key to know which account to use
  3. using SSH keyring with both keys in it
    • keyring presents keys in internal order

git needs to be explicitly configured to use a given SSH key

solution

Test each account to ensure the "welcome!" message reflect the correct user:

$ ssh -i ~/.ssh/id_rsa_user1 -T git@gitlab.com
Welcome to GitLab, @user1!

$ ssh -i ~/.ssh/id_rsa_user2 -T git@gitlab.com
Welcome to GitLab, @user2!

Within a cloned repository, locally configure that repository to use a specific key:

$ git clone git@gitlab.com:user1/foo.git
$ cd foo
$ git config core.sshCommand "ssh -i ~/.ssh/id_rsa_user1 -F /dev/null"

and/or

$ git clone git@gitlab.com:user2/bar.git
$ cd bar
$ git config core.sshCommand "ssh -i ~/.ssh/id_rsa_user2 -F /dev/null"

This adds the setting to the local .git/config file like so:

[core]
        sshCommand = ssh -i ~/.ssh/id_user73 -F /dev/null
        ...

initial clone

If the initial clone requires a specific SSH key before the above is available, it must be exported to the environment first.

GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa_user99 -F /dev/null" \
  git clone git@gitlab.com:user99/privatestuff.git

Any option for SSH can be used (ssh -o StrictHostKeyChecking=no ... e.g.) as needed.