Use a specific SSH key for a certain git repo
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 [email protected]
it shall use [email protected]
instead.
By the way, this concept also works with other git foundries, such as GitHub.
Assumptions
You have two ssh keys:
~/.ssh/[email protected]
is your work ssh key.~/.ssh/[email protected]
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/[email protected]
Host private.gitlab.com
Hostname gitlab.com
IdentitiesOnly yes
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]