gitgithubsshssh-keys

Multiple git account associated to folders and SSH Confiog


I'm working with multiple GitHub account (let's say userA and userB ...). My folder architecture is

Projects/
 |- userA/
     |- projectA1/
     |- projectA2/
     |- ... All the repository accessible by userA
 |- userB/
     |- projectB1/
     |- projectB2/
     |- ... All the repository accessible by userB
 |- ...

Some users may need an SSH config, some others may not.

Is it possible to have a set up so when I'm working anywhere under the folder userA, then the git user is userA, and similarly, when working under a folder userX, the git user is userX?


Solution

  • With the help of @phd's comment and those other answers

    here is how I did it.

    I didn't manage to do the set up with some accounts not using ssh key. So I made all of them use one. In this example I gave userA and userB.

    1. Update the ~/.giconfig to use different .gitconfig files depending on the folder:

    ~/.gitconfig:

    [includeIf "gitdir:~/userA/"]
        path = ~/userA/.gitconfig-user-a
    
    [includeIf "gitdir:~/userB/"]
        path = ~/userB/.gitconfig-user-b
    

    ~/userA/.gitconfig-user-a:

    [user]
        name = userA
        email = user.a@email.com
    

    ~/userB/.gitconfig-user-b:

    [user]
        name = userB
        email = user.b@email.com
    
    1. Follow the steps of Generating a new SSH key and adding it to the ssh-agent. One for each user:
    ssh-keygen -t ed25519 -C "user.a@email.com" -f "User/valentin/.ssh/id_ed25519_user_a"
    ssh-keygen -t ed25519 -C "user.b@email.com" -f "User/valentin/.ssh/id_ed25519_user_b"
    
    1. Update your ~/.ssh/config:
    Host github_user_a
      HostName github.com
      AddKeysToAgent yes
      UseKeychain yes
      IdentityFile ~/.ssh/id_ed25519_user_a
    
    Host github_user_b
      HostName github.com
      AddKeysToAgent yes
      UseKeychain yes
      IdentityFile ~/.ssh/id_ed25519_user_b
    
    
    1. Add the ssh keys to the related github accounts. You can follow Adding a new SSH key to your GitHub account.

    For user_x, copy the key with

    pbcopy < ~/.ssh/id_ed25519_user_x.pub
    

    And paste it in github.com > Settings > Access > SSH and GPG keys > SSH keys > New SSH key > Key:

    Add new SSH key screenshot

    1. When cloning a repo (userA/repo_a in the folder userA for example), use SSH instead of https, and replace github.com with github_user_a:
    git clone git@github_user_a:userA/repo_a.git