Use a specific SSH key for a certain git repo
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 git@gitlab.com
it shall use git@private.gitlab.com
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:
~/.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 three lines are optional, but recommended
AddKeysToAgent yes
UpdateHostKeys yes
HashKnownHosts yes
Host gitlab.com
IdentitiesOnly yes
# Main gitlab.com SSH key
IdentityFile ~/.ssh/id_ed25519_work@gitlab.com
Host private.gitlab.com
IdentitiesOnly yes
# Translate private.gitlab.com back to gitlab.com
Hostname gitlab.com
# Other gitlab.com SSH key
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