Using the Correct SSH Keys for Multiple Hosts

I recently ran into the issue of managing my ssh keys across different organizations. And yes by recently I do mean that I have been using my personal ssh key at work too… What we want to do is separate your personal ssh key from your work ssh key, and have git respect this by project.

I’ll be using gitlab in the examples. Replace with github, bitbucket, etc as you see fit.

Create SSH Keys

Let’s say we have created two keys using the following commands:

# Accept all defaults for this exercise, normally use a passphrase
$ ssh-keygen -t rsa -f personal
$ ssh-keygen -t rsa -f jake-work

This will generate the expected filename & filename.pub files in your ~/.ssh directory.

SSH Config

Now we need to edit the ~/.ssh/config file:

$ nano ~/.ssh/config
# ~/.ssh/config
# Personal account
Host gitlab.com_jakeklassen
  HostName gitlab.com
  User jakeklassen
  IdentityFile ~/.ssh/personal

# Work
Host gitlab.com_jklassen
  HostName gitlab.com
  User jklassen
  IdentityFile ~/.ssh/jake-work

I like to have User & Host reflect my username on the host (gitlab.com in this case).

Clone and Configure Git Repositories

Clone

To clone a repository we can use the following command:

# Replace username and repo with the respective remote values.
$ git clone git@gitlab.com_jklassen:username/repo.git path

Update Existing

If we wanted to update the remote origin of our repository, we could use the following command:

# Replace username and repo with the respective remote values.
$ git remote set-url origin git@gitlab.com_jklassen:username/repo.git

Notice how the portion between the @ & : characters reflects the Host values from ~/.ssh/config.

Update Git Config

Normally you’ll see tutorials use:

$ git config --global user.name 'Your Name'
$ git config --global user.email 'you@personal.com'

This is great for your most commonly used account - in my case my personal account, but you should now use this per project when needed.

If I was in one of my work projects I would use:

$ git config user.name 'Your Name'
$ git config user.email 'you@work.com'

We’re just omitting the --global flag and providing the proper values.

 
comments powered by Disqus