Specify a specific SSH private key for git pull/git clone

Want to help support this blog? Try out Oh Dear, the best all-in-one monitoring tool for your entire website, co-founded by me (the guy that wrote this blogpost). Start with a 10-day trial, no strings attached.

We offer uptime monitoring, SSL checks, broken links checking, performance & cronjob monitoring, branded status pages & so much more. Try us out today!

Profile image of Mattias Geniar

Mattias Geniar, November 19, 2019

Follow me on Twitter as @mattiasgeniar

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.

Want to subscribe to the cron.weekly newsletter?

I write a weekly-ish newsletter on Linux, open source & webdevelopment called cron.weekly.

It features the latest news, guides & tutorials and new open source projects. You can sign up via email below.

No spam. Just some good, practical Linux & open source content.