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.

Via ssh-agent

How to specify an alternate SSH key with git using ssh-agent

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

INFO

$KEY_FILE must be the full path of a private key (e.g., ~/.ssh/id_rsa or ~/.ssh/gpg_auth_key.pub).

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

Link to original

Via GIT_SSH_COMMAND

How to specify an alternate SSH key using the GIT_SSH_COMMAND variable

With a secret SSH key:

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

INFO

$KEY_FILE must be the full path of a private key (e.g., ~/.ssh/id_rsa or ~/.ssh/gpg_auth_key.pub).

IMPORTANT

If you’re running ssh-agent, then setting the config directive IdentityAgent=none is important as otherwise the key(s) already stored in the agent will take precedence over $KEY_FILE.

With KeePassXC or a GPG authentication subkey referenced using a public $KEY_FILE, setting IdentityAgent=none is unnecessary:

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

Via a config directive

How to specify an alternate SSH key as a Git config directive

With a secret SSH key:

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

INFO

$KEY_FILE must be the full path of a private key (e.g., ~/.ssh/id_rsa or ~/.ssh/gpg_auth_key.pub).

IMPORTANT

If you’re running ssh-agent, then setting the config directive IdentityAgent=none is important as otherwise the key(s) already stored in the agent will take precedence over $KEY_FILE.

With KeePassXC or a GPG authentication subkey referenced using a public $KEY_FILE, setting IdentityAgent=none is unnecessary:

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

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

Link to original