Search code examples
gitgithubgitlabssh-keys

SSH Key Managment for Multiple Git Accounts


I am trying to create Multiple SSH keys for multiple git accounts. For now, I have one Github account and two Gitlab accounts, I could not find the guide for Multiple accounts across multiple git platforms. Can you help me with it.

Keys are:

  1. id_rsa_github git username is demetere
  2. id_rsa_gitlab git username is demetere
  3. id_rsa_gitlab_identomat git username is demetere._

I literally need help with agent and cloning and pushing permissions. I generated 3 keys for each account and added them to accounts and also added to the agent. The only thing left is the config file and also if there is anything specific I need to do when cloning repos and pushing.

Also when I am a contributor to other users' repos how can I clone that with the correct Host? Thanks


Solution

  • The main idea is to use ~/.ssh/config to assign a "Host" entry to each of your accounts:

    Host ghuser1
      Hostname github.com
      User git
      IdentityFile ~/.ssh/key1
    
    Host gluser1
      Hostname gitlab.com
      User git
      IdentityFile ~/.ssh/keyg1
    
    Host gluser2
      Hostname gitlab.com
      User git
      IdentityFile ~/.ssh/keyg2
    

    That means, for cloning, you will need to use that "Host" entry:

    git clone ghuser1:me/MyRepo
    

    You can also test the authentication with:

    ssh -Tv ghuser1
    ssh -Tv gluser1
    ssh -Tv gluser2
    

    A few notes:

    • the User is always git, never your GitHub or GitLab account username.
    • the authentication is needed in order to determine if your account has the right to access a private repository (you must be added as collaborator).
      For a public repository, this is less important.