Close

05/31/2020

How to use multiple SSH keys on a Mac with Github or Gitlab

A quick note on how to use multiple SSH Keys (Identities) on one machine.

A short note on the use case

Why would you want to use multiple keys on a machine you ask? There are several reasons, one being perceived security and another being convenience. Using just one Identity makes everything easier and you don’t have to manage several Identities You can read more here and here.

My use case would be that of convenience. I just want to separate work from personal projects and I would like to use a separate key (non-work related) with those projects

1. Create a new public key

ssh-keygen -t rsa -C "your_email@youremail.com"

This public key can be in any path, not just in ~/.ssh/ as default/ recommended.

For security, it is recommended that you assign a unique password to this key.

Add all the keys to your cached keys

ssh-add path-to-key

For example, if you have your new key in ~/Documents/ssh_keys/new_key you would need to run ssh-add ~/Documents/ssh_keys/new_key . If you assigned a password in Setup 1, you will be asked for it.

Step 3: Update/ Create your ssh config

nano ~/.ssh/config

If you already have entries in your ssh config, just add a new entry at the end of the file. If your file is empty or you didn’t have any before, just add the following.

Host gitlab-diego
	HostName gitlab.com # or github.com or any other domain
	User your-username # usually the one you use with that domain
	IdentityFile path-to-key

With the example data for GitLab and user diego this entry would look like the following:

Host gitlab-diego
	HostName gitlab.com
	User diego
	IdentityFile ~/Documents/ssh_keys/new_key

To save and close just press ctrl + o and enter

To exit nano press ctrl + x.

Step 4: Add the key to GitLab, GitHub or other services

In my case, I wanted to use the new key with GitLab. They have great instructions on how to do that but, for convenience, I list the steps here:

  1. Copy your new key to the clipboard.
  2. Log in into gitlab.com and go to https://gitlab.com/profile/keys
  3. Paste the key into the text box and click on „Add key“

Now you may clone a repository using this new key.

References and further reading

%d bloggers like this: