Skip to content

Instantly share code, notes, and snippets.

@dotspencer
Last active March 7, 2024 15:01
Show Gist options
  • Save dotspencer/bcd7588716082f03798beed62006fc1c to your computer and use it in GitHub Desktop.
Save dotspencer/bcd7588716082f03798beed62006fc1c to your computer and use it in GitHub Desktop.
Multiple Gitlab accounts with multiple ssh keys

Gitlab won't allow reuse of a public ssh key for multiple accounts. To get around this you need to create a second ssh key for the second account.

Create or modify your ~/.ssh/config file:

# normal                                                                                                                                                                  
Host gitlab.com-work_username
     HostName gitlab.com
     PreferredAuthentications publickey
     IdentityFile ~/.ssh/id_rsa

# second                                                                                                                                                                  
Host gitlab.com-personal_username
     HostName gitlab.com
     PreferredAuthentications publickey
     IdentityFile ~/.ssh/second_key

Check that both authenticate correctly with Gitlab:

ssh -T git@gitlab.com-work_username
ssh -T git@gitlab.com-personal_username

Then in the repo you want to use the second account for, edit the .git/config file:

[remote "origin"]
        url = git@gitlab.com-personal_username:group-name/repo-name.git

Added the -personal_username after gitlab.com


To clone the repo initially you can use:

GIT_SSH_COMMAND='ssh -i ~/.ssh/<second_private_key> -o IdentitiesOnly=yes' git clone <repo_url.git>
@gzimbron
Copy link

gzimbron commented Mar 2, 2022

Thanks.

@dozyc
Copy link

dozyc commented Apr 11, 2022

Thanks for this. If you're going through the trouble of making the Host entries in ~/.ssh/config, you could set User to git, then it's not needed on the command line or in the git remote config

@skhashaev
Copy link

What if it doesn't work for me? Both of the accounts doesn't authenticate

@skhashaev
Copy link

Thanks for this. If you're going through the trouble of making the Host entries in ~/.ssh/config, you could set User to git, then it's not needed on the command line or in the git remote config

Worked, when I changed PreferredAuthentications publickey to User git

@HongtaoYang
Copy link

Why we don't need to also add -work_username to the remote url for the work repos?

@cristihainic
Copy link

many thanks 👍

@ikbal-nayem
Copy link

Thank you so mush.

@LuanNguyenCong
Copy link

Thanks you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment