How to Manage Multiple SSH Keys for GitHub

Short tutorial on how to structure projects and setup multi-user Git SSH workflow.

banner1Photo by Michel Didier Joomun

When using a single machine with multiple git accounts you might encounter some obstacles with SSH setup. The easiest way to achieve a multi-user setup is to structure git repositories by respective directories, e.g.:

2├── work
3│ ├── enterprise-fiz-buz
4│ └── ...
5└── personal
6 ├── karolis.sh
7 └── ...

This short tutorial will help you setup SHH for such workflow.

Generating a new SSH key

To generate a new SSH key use the provided template script (or check the docs):

1export EMAIL=[email protected]
2export SSH_FILE=$HOME/.ssh/id_rsa_work
3ssh-keygen -t rsa -b 4096 -C $EMAIL -f $SSH_FILE
4ssh-add -K $SSH_FILE
5echo "🔽 PUBLIC KEY BELOW 🔽" && cat $SSH_FILE.pub
6pbcopy < $SSH_FILE.pub

What's left is to add the SSH key to your GitHub/GitLab/etc. account.

Multi-user Git SSH setup

The general idea is that you use specific ssh command based on your working directory with the help of git includes.

Update the ~/.gitconfig file:

2 name = Karolis Šarapnickis
5 sshCommand = ssh -i ~/.ssh/id_rsa
7 default = current
8[includeIf "gitdir:~/projects/work/"]
9 path = ~/.gitconfig.work

And the ~/.gitconfig.work file:

4 sshCommand = ssh -i ~/.ssh/id_rsa_work

And that's it! Appropriate SSH setup will be used based on directory location, no extra actions are needed.

Karolis Šarapnickis 🇱🇹

Engineering Manager @ Nord Security

I build stuff using JavaScript and share my findings from time to time. I hope you will find something useful here.