How to use multiple ssh keys for multiple gitlab accounts with the same host

Osama Mohamed picture Osama Mohamed · Jun 18, 2016 · Viewed 9.8k times · Source

I want to use 2 accounts in Gitlab website, every account with a different ssh key

I generated the keys successfully and add them in ~/.ssh folder I created ~/.ssh/config file and use one of them , it's works good I can also make swapping between the two keys by editing the ~/.ssh/config file

The problem is : I want to use them in the same time , but all the tutorials i found taking about different hosts :/

actually my two accounts are in the same host

how can i edit the ~/.ssh/config file to accept two accounts for the same host

Note: I read this question but i can't get help from it

My two accounts are username1 and username2 repo URL looks like : [email protected]:username1/test-project.git

My current ~/.ssh/config file:

Host gitlab.com-username1
  HostName gitlab.com
  User git
  IdentityFile ~/.ssh/id_rsa

Host gitlab.com-username2
  HostName gitlab.com
  User git
  IdentityFile ~/.ssh/id_rsa_username2

Update 1:

1) When I use one key in the ~/.ssh/config file , everything works perfect (but it's very boring to update it every time i want to change the user i use)

2) When i use this lines ssh -T [email protected] ssh -T [email protected] its works good and return a welcoming message

From 1) and 2) , i think the problem is definitely from the ~/.ssh/config file , specifically in Host variable

Update 2: (the solving) the solving was to edit the .git/config file from [remote "origin"] url = [email protected]:username1/test-project.git to [remote "origin"] url = [email protected]:username1/test-project.git

and do the same for the username2

Answer

Jakuje picture Jakuje · Jun 18, 2016

You have got complete ssh configuration. First of all, check if it works:

ssh -T [email protected]
ssh -T [email protected]

should succeed in both cases. If not, the keys are not set up correctly. Verify that the keys are on gitlab for respective users.

If it works, move on to your git repository and open .git/config. It will have some part like:

[remote "origin"]
  url = [email protected]:username1/test-project.git

Replace it with

[remote "origin"]
  url = [email protected]:username1/test-project.git

(or username1 if you want to connect using this username). Then it should allow you to push.