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

Oh Dear! monitors your entire site, not just the homepage. We crawl and search for broken pages and mixed content, send alerts when your site is down and notify you on expiring SSL certificates.

Start your free 10 day trial! »

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.