How to Manage Multiple SSH Keys for GitHub, GitLab, etc.
Short tutorial on how to structure projects and setup multi-user Git SSH workflow.
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.:
1projects2├── work3│ ├── enterprise-fiz-buz4│ └── ...5└── personal6 ├── karolis.sh7 └── ...
This short tutorial will help you set up SHH for such workflow.
Generating a new SSH key
To generate a new SSH key, use the provided template script (or check the docs):
2export SSH_FILE=$HOME/.ssh/id_rsa_work3ssh-keygen -t rsa -b 4096 -C $EMAIL -f $SSH_FILE4ssh-add -K $SSH_FILE5echo "🔽 PUBLIC KEY BELOW 🔽" && cat $SSH_FILE.pub6pbcopy < $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:
1[user]2 name = Karolis Šarapnickis3 email = [email protected]4[core]5 sshCommand = ssh -i ~/.ssh/id_rsa6[push]7 default = current8[includeIf "gitdir:~/projects/work/"]9 path = ~/.gitconfig.work
And the ~/.gitconfig.work
file:
1[user]2 email = [email protected]3[core]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.
Software Engineer
I build stuff using JavaScript and share my findings from time to time. I hope you will find something useful here.