Separate SSH Key for different Gitlab/Github accounts

March 01, 2018

Context I have one Gitlab account for personal and one for company use. To make sure my commits line up correctly with the email used in the SSH keys, I decided to have separate SSH keys for each account. The way it works is you need to create two sets (public and private) of keys. And then modify the SSH config and git config to get them to work.

Generating SSH Keys

I’m doing this on a Lubuntu machine. These may also work on an OSX machine.

ssh-keygen -t rsa -C "me@personal-email.com" -b 4096

ssh-keygen -t rsa -C "me@work-email.com" -b 4096

Name them appropriately, when it asks. I named mine gitlab-personal and gitlab-work. I also don’t use a passphrase.

Modify SSH config

Once complete, open up your ~/.ssh/config file create two entries.

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


Host gitlab.com-work
    HostName gitlab.com
    User git
    IdentityFile ~/.ssh/gitlab-work

You need to add “-personal” and a “-work” after the hostname to differentiate the two SSH profiles. We’ll see how these come into play next.

Modify Git config

Last step is modifying the git config file of the repo you’re working on. The config file is located here .git/config. In it you’ll see a section like this (assuming you’ve setup your remote repo and named it ‘origin’):

[remote "origin"]
    url = git@gitlab.com:kar.ai/www.git
    fetch = +refs/heads/*:refs/remotes/origin/*

Now you need to add the “-personal” or “-work” in the URL as needed. In my case, this was a personal project, so:

[remote "origin"]
    url = git@gitlab.com-personal:kar.ai/www.git
    fetch = +refs/heads/*:refs/remotes/origin/*

Now you can push to the Gitlab repository, and it’ll use the right SSH key to do so. Of course, you’ll have to set up the SSH key on Gitlab as well. Refer to the documentation.

I'll tell you when I post stuff.

Subscribe to get my latest posts by email.