Use a specific SSH key for a certain git repo

Posted on Oct 30, 2024

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

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 for one specific repository, that whenever it sees [email protected] it shall use [email protected] instead.

OpenSSH will then translate that back to gitlab.com. But it will use the correct SSH key in the process.

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

Assumptions

You have two ssh keys:

OpenSSH config

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

# These three lines are optional, but recommended
AddKeysToAgent yes
UpdateHostKeys yes
HashKnownHosts yes

Host gitlab.com
  IdentitiesOnly yes
  # Main gitlab.com SSH key
  IdentityFile ~/.ssh/[email protected]

Host private.gitlab.com
  IdentitiesOnly yes
  # Translate private.gitlab.com back to gitlab.com
  Hostname gitlab.com
  # Other gitlab.com SSH key
  IdentityFile ~/.ssh/[email protected]

git config

In that private git repository, configure the following.

git config [email protected]:.insteadOf [email protected]:

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 [email protected]