Use multiple ssh-keys for different GitHub accounts on the same computer
At joining my current work place, I was asked to create a new GitHub account before I can be a member of the company’s GitHub organization and in turn get access to all the private project repositories.
It wasn’t until I left the work laptop in my locker but still needed to get something done that I felt the need to manage both of my GitHub accounts on my personal laptop (who needs work-life balance?)
To make things more complicated, the project I’m working on references other private repositories in its
package.json’s dependencies block and needs to access them at
npm install , which defaults to using my personal GitHub account’s ssh-key.
After some trials and failures, here’s how I finally got it to work:
1. Create a new ssh-key and add it to the work GitHub account
$ ssh-keygen -t rsa -b 4096 -C "my_work_email@my_company.com"
Say the new ssh-key was named “work_rsa”, now copy the content of the newly generated public key file (work_rsa.pub in this example) and paste it to the work GitHub account’s setting page as described in the GitHub help page.
2. Modify the ssh config file (
Open the config file in a text editor (create it if there isn’t one in the ~/.ssh folder yet) and add the following to it:
# Personal GitHub account
IdentityFile ~/.ssh/id_rsa# Work GitHub account
3. Clone the work project repo (with a slightly different address)
To clone the work project repo using the new ssh-key we need to tweak a little bit on the repo’s ssh address. The host url needs to match the Host defined in the ssh config file from last step, namely, where in the address there is
github.com, replace it with
E.g., with the following private repo ssh address we get from GitHub:
email@example.com:[my work GitHub group]/[my project].git
We need to tweak its address like this before we can
git clone it:
firstname.lastname@example.org:[my work GitHub group]/[my project].git
$ git clone email@example.com:[my work GitHub group]/[my project].git
4. Modify the package.json to install the private repo dependencies
In the project that cloned locally, find the private repo dependencies in its package.json and do the same modification to their repo address as in step 3 (I wouldn’t commit these modifications since it breaks everything for other people who are also working on this project):
"private-module": "git+ssh://firstname.lastname@example.org/[private module name].git
*It might be necessary to first do a manual install for one of the private modules in terminal:
$ npm install git+ssh://email@example.com/[private module name]
So that the private repos get recognized in the ssh
known_hosts and can be accessed during npm installing the project dependencies.