Use an Alternate SSH Key with Git

author: Nathan Acks

By default, Git only uses you primary SSH key when cloning. While there’s no way to get git to try alternate keys if the first key fails, there are a few ways you can force it to use a particular key on a per-repository basis.

Note that in the below examples $KEY_FILE must be the full path of a private key (e.g., ~/.ssh/id_rsa or ~/.ssh/gpg_auth_key.pub). If you’re running ssh-agent (or a work-alike) and using a key generated by ssh-keygen, then setting the config directive IdentityAgent=none is important in the second two methods as otherwise the key(s) already stored in the agent will take precedence over $KEY_FILE. However, when using a GPG authentication subkey via gpg-agent with SSH (in which case you’ll be referencing the public part of that key, rather than a SSH secret key) this directive should not be included (gpg-agent will do the right thing).

Via ssh-agent

ssh-agent bash -c "ssh-add $KEY_FILE && git $COMMAND"

This is useful for running multiple, one-off commands. Note that this method won’t work when used with GPG authentication subkeys.

Via GIT_SSH_COMMAND

With a secret SSH key:

GIT_SSH_COMMAND="ssh -i $KEY_FILE -F /dev/null -o IdentityAgent=none" git $COMMAND

With KeePassXC or a GPG authentication subkey referenced using a public $KEY_FILE:

GIT_SSH_COMMAND="ssh -i $KEY_FILE -F /dev/null" git $COMMAND

Via a Config Directive

With a secret SSH key:

git config core.sshCommand "ssh -i $PUBLIC_KEY_FILE -F /dev/null -o IdentityAgent=none"

With KeePassXC or a GPG authentication subkey referenced using a public $KEY_FILE:

git config core.sshCommand "ssh -i $PUBLIC_KEY_FILE -F /dev/null"

This is useful for ongoing work, but only works on existing repositories.