Multiple Gitlab/Github accounts with different SSH keys (MacOS/Linux)

Oftentimes when you work for multiple clients, or when you have a personal and a work account on Github, you need to use different SSH keys for different accounts. This is a guide on how to do that on MacOS and Linux.

I make use of this repository https://github.com/tiagomapmarques/ssh-tools to manage my SSH keys. After installing it using the instructions on the README, you can use ssh-switch <profile> to switch between different SSH keys.

Existing keys

If you have existing SSH keys, managed using the ~/.ssh/config file, you can remove them and use the ssh-switch command instead.

Next to this, if you have used ssh-add to add your SSH keys to the SSH agent, you can remove them using ssh-add -D. The default SSH key (id_rsa) will be then be used when you connect to a remote server.

Thoughts

The alternative is specifying the Host and IdentityFile in the ~/.ssh/config file. Using that methods, you will need to specify a non-default hostname when cloning a repository.

Host github.com
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_rsa

Host github.com-personal
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_rsa_personal

Cloning a repository using the personal account would then be done using:

git clone [email protected]/somerepo.git

With the aforementioned method (ssh-tools), you do not need to specify the SSH Host Alias when cloning a repository. However, you do need to run the ssh-switch command every time you want to switch between account contexts.

Using Playwright on OpenshiftJS/TS Awaiting multiple items in a loop