DEV Community

Cover image for How to Manage Multiple SSH Keys for GitHub, GitLab, etc.
Karolis Šarapnickis
Karolis Šarapnickis

Posted on • Originally published at karolis.sh

17 3

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.:

projects
├── work
│   ├── enterprise-fiz-buz
│   └── ...
└── personal
    ├── karolis.sh
    └── ...
Enter fullscreen mode Exit fullscreen mode

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):

export EMAIL=karolis.sarapnickis@work.com
export SSH_FILE=$HOME/.ssh/id_rsa_work
ssh-keygen -t rsa -b 4096 -C $EMAIL -f $SSH_FILE
ssh-add -K $SSH_FILE
echo "🔽 PUBLIC KEY BELOW 🔽" && cat $SSH_FILE.pub
pbcopy < $SSH_FILE.pub
Enter fullscreen mode Exit fullscreen mode

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:

[user]
  name = Karolis Šarapnickis
  email = pastas.k@gmail.com
[core]
  sshCommand = ssh -i ~/.ssh/id_rsa
[push]
  default = current
[includeIf "gitdir:~/projects/work/"]
  path = ~/.gitconfig.work
Enter fullscreen mode Exit fullscreen mode

And the ~/.gitconfig.work file:

[user]
  email = karolis.sarapnickis@work.com
[core]
  sshCommand = ssh -i ~/.ssh/id_rsa_work
Enter fullscreen mode Exit fullscreen mode

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

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs