I’ve been moving some projects around lately and found myself in need of a weird thing I hadn’t considered before: specifying a specific SSH private key for running things like git clone
or git pull
.
Luckily, it wasn’t that hard.
Using a specific environment variable
You can overwrite the SSH command that’s being used by git, by giving it a custom environment variable.
Consider this example:
$ GIT_SSH_COMMAND='ssh -i /var/www/html/ma.ttias.be/.ssh/id_rsa' git pull
This runs the git pull
command, but it does so by using a very specific private key located in /var/www/html/ma.ttias.be/.ssh/id_rsa
.
The GIT_SSH_COMMAND
is available in modern git versions and can be used to overwrite the identity (-i
) or things like the SSH port.
A custom SSH config
An alternative approach, but one I found less useful for quick-and-dirty git operations, is to modify your SSH client config.
You can specify an alias for SSH operations and use that to point to the correct identity file.
$ cat ~/.ssh/config
Host yourserver
Hostname something.domain.tld
IdentityFile /var/www/html/ma.ttias.be/.ssh/id_rsa
IdentitiesOnly yes
Now, if you git clone from that specific alias, it will use your private key.
$ git clone git@yourserver:yourrepo.git
The yourserver translates to the alias used in ~/.ssh/config
.