Use a specific SSH key for a certain git repo

Posted on Oct 30, 2024

At work, I use a separate account for GitLab. It has its own SSH key. Whenever I want to push code to my private GitLab repositories, I want to use the SSH key of my private account.

Concept

We’re going to use a clever combination of OpenSSH configuration and git configuration.

In OpenSSH, we’ll create a virtual host. The virtual host will be _private.gitlab.com. We’ll simply tell OpenSSH that whenever it sees private.gitlab.com, it must connect to gitlab.com instead.

In git, we’ll create a virtual URL. We’ll tell git, that whenever it sees git@gitlab.com it shall use git@private.gitlab.com instead.

By the way, this concept also works with other git foundries, such as GitHub.

Assumptions

You have two ssh keys:

  • ~/.ssh/id_ed25519_work@gitlab.com is your work ssh key.
  • ~/.ssh/id_ed25519_private@gitlab.com is you private ssh key.

OpenSSH config

First, edit ${HOME}/.ssh/config.

# These are optional
AddKeysToAgent yes
UpdateHostKeys yes
HashKnownHosts yes

Host gitlab.com
  # Default SSH key
  IdentityFile ~/.ssh/id_ed25519_work@gitlab.com

Host private.gitlab.com
  Hostname gitlab.com
  IdentitiesOnly yes
  IdentityFile ~/.ssh/id_ed25519_private@gitlab.com

git config

In that private git repository, configure the following.

git config url.git@private.gitlab.com:.insteadOf git@gitlab.com:

Hint: You can also change your committer name and/or email only for one repository the same way:

git config user.name 'l33t h4x0r'
git config user.email l33t@h4x0r.email