DEV Community

Ajmal Muhammed
Ajmal Muhammed

Posted on Edited on

Setup Multiple SSH Keys

How to Manage Multiple SSH Keys

If you have multiple keys, create an SSH config file as follow:

nano ~/.ssh/config
Enter fullscreen mode Exit fullscreen mode

Add the following according to your key name:

Host gitlab.com
    HostName gitlab.com
    User git
    IdentityFile ~/.ssh/id_ed25519
    AddKeysToAgent yes

Host github.com
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_ed25519
    AddKeysToAgent yes

Enter fullscreen mode Exit fullscreen mode

What if we have multiple GitLab or GitHub keys?

Edit the config as follows:

# Personal GitLab
Host gitlab.com-personal
    HostName gitlab.com
    User git
    IdentityFile ~/.ssh/gitlab_personal
    AddKeysToAgent yes

# Work GitLab
Host gitlab.com-work
    HostName gitlab.com
    User git
    IdentityFile ~/.ssh/gitlab_work
    AddKeysToAgent yes

# Personal GitHub
Host github.com-personal
    HostName github.com
    User git
    IdentityFile ~/.ssh/github_personal
    AddKeysToAgent yes

# Work GitHub
Host github.com-work
    HostName github.com
    User git
    IdentityFile ~/.ssh/github_work
    AddKeysToAgent yes
Enter fullscreen mode Exit fullscreen mode

Note: Here, you need to specify custom name for the Host.

Set proper permissions

chmod 600 ~/.ssh/config
chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_ed25519
chmod 644 ~/.ssh/id_ed25519.pub
Enter fullscreen mode Exit fullscreen mode

Clone/Configure repositories with the right host

Personal GitLab project
git clone git@gitlab.com-personal:username/repo.git

Work GitLab project
git clone git@gitlab.com-work:company/repo.git

Personal GitHub project
git clone git@github.com-personal:username/repo.git

Work GitHub project
git clone git@github.com-work:company/repo.git
Enter fullscreen mode Exit fullscreen mode

Note: above examples are according to the previous config file

For existing repositories:

Check current remote

git remote -v
Enter fullscreen mode Exit fullscreen mode

Change to personal GitLab

git remote set-url origin git@gitlab.com-personal:username/repo.git
Enter fullscreen mode Exit fullscreen mode

Change to personal GitHub

git remote set-url origin git@github.com-personal:username/repo.git

Enter fullscreen mode Exit fullscreen mode

Top comments (0)