Multiple SSH key for different github/gitlab account

Elvis Ciotti
2 min readJan 19, 2022

--

How to configure each repository to use a different key belonging to a different gitlab or github account.

Gitlab (and also Github, IIRC) don’t let you add the same key to different accounts of yours (e.g. your company and your personal account). So, if you want to use repositories, you’ll have to set separate keys and configure each repository to use its own key.

Gitlab Error “Fingerprint has already been taken” then adding an SSH key used by another user

How to fix

Assume you have an existing key ~/.ssh/id_rsa used for your gitlab work account.

Create and upload key for personal account

If you do’t have it already, create a second key for your personal account with which you can checkout repository from your gitlab personal account.

sh-keygen -t rsa
# store into ~/.ssh/id_rsa_personal

And add it into into github/gitlab under your personal account.

They key must be loaded when you open the shell. If ssh-add -ldoes not list your new key at shell opening time, you can add the AddKeysToAgentSSH config option (see later) or use this commands on the shell init script

eval $(ssh-agent) > /dev/null
ssh-add ~/.ssh/id_rsa &> /dev/null
ssh-add ~/.ssh/id_rsa_personal &> /dev/null

Set SSH host config rules

Prepend the following to your ~/.ssh/config.

Host gitlab.personal.com
HostName gitlab.com
# User git # didn't seem to make a difference
IdentityFile ~/.ssh/gitlab
Host gitlab.com
HostName gitlab.com
# User git # didn't seem to make a difference
IdentityFile ~/.ssh/id_rsa
Host *
AddKeysToAgent yes
UseKeychain yes
# IdentityFile ~/.ssh/id_rsa # MUST BE DISABLED
UseKeychain yes
ServerAliveInterval 30
ServerAliveCountMax 2

Important: there should no be a Host *rule that specifies another key, otherwise that will override you setting. If you also use other hosts, specify them along with the key. There is a more advanced syntax for host matching, but I want to keep this example simple.

You can how checkout the repository using the modified host.

git clone git@gitlab.personal.com:yourUsername/yourRepo.git

Comment if not working. Clap if useful. Thanks for reading

--

--

Elvis Ciotti
Elvis Ciotti

Written by Elvis Ciotti

Software Contractor — Java, Spring, k8s, AWS, Javascript @ London - hire me at https://elvisciotti.github.io/

No responses yet