Search code examples
sshgitlabssh-keys

Multiple ssh key for the same gitlab host


I'm having two gitlab.com accounts and since GitLab does not allow me to use the same ssh key, I have to generate two ssh keys.

I'm trying to config the ssh, here is my config:

Host company
    HostName gitlab.com
    User vunh
    IdentityFile ~/.ssh/id_rsa
Host private
    Hostname gitlab.com
    User hoangvu271297
    IdentityFile ~/.ssh/private

Both accounts are logged in to the same domain gitlab.com.

Previously, I did not config anything because I only use the id_rsa. Until now the id_rsa still works fine but I can not find a way out to clone the project using the private one. I tried many configs on the Internet but no one works.

Is there any way to deal with this situation? I knew it is configurable if there are two different hosts such as gitlab.com and work.gitlab.com

Many thanks.


Solution

  • The documentation covers this scenario.

    You should setup your ssh config using two different Host configurations for each user. Say, user_1.gitlab.com and user_2.gitlab.com. You can use whatever value you want here, these are just examples.

    # User1 Account Identity
    Host user_1.gitlab.com
      Hostname gitlab.com
      PreferredAuthentications publickey
      IdentityFile ~/.ssh/example_ssh_key1
    
    # User2 Account Identity
    Host user_2.gitlab.com
      Hostname gitlab.com
      PreferredAuthentications publickey
      IdentityFile ~/.ssh/example_ssh_key2
    

    You then use these Host keys when setting up your git repos.

    For example, to clone using user_1 account:

    git clone git@user_1.gitlab.com:gitlab-org/gitlab.git
    

    Note that you should NOT provide your username as the User configuration in your SSH config. The username you use to connect to GitLab over SSH is always git. The identity file (ssh key), not ssh user, determines the GitLab user account.