Specify an SSH key for git push for a given domain
Configure your repository using git config
git config --add --local core.sshCommand 'ssh -i <<<PATH_TO_SSH_KEY>>>'
This applies to your local repository only.
Even if the user and host are the same, they can still be distinguished in ~/.ssh/config
. For example, if your configuration looks like this:
Host gitolite-as-alice
HostName git.company.com
User git
IdentityFile /home/whoever/.ssh/id_rsa.alice
IdentitiesOnly yes
Host gitolite-as-bob
HostName git.company.com
User git
IdentityFile /home/whoever/.ssh/id_dsa.bob
IdentitiesOnly yes
Then you just use gitolite-as-alice
and gitolite-as-bob
instead of the hostname in your URL:
git remote add alice git@gitolite-as-alice:whatever.git
git remote add bob git@gitolite-as-bob:whatever.git
Note
You want to include the option IdentitiesOnly yes
to prevent the use of default ids. Otherwise, if you also have id files matching the default names, they will get tried first because unlike other config options (which abide by "first in wins") the IdentityFile
option appends to the list of identities to try. See: https://serverfault.com/questions/450796/how-could-i-stop-ssh-offering-a-wrong-key/450807#450807
You can utilize git environment variable GIT_SSH_COMMAND
. Run this in your terminal under your git repository:
GIT_SSH_COMMAND='ssh -i ~/.ssh/your_private_key' git submodule update --init
Replace ~/.ssh/your_private_key
with the path of ssh private key you wanna use. And you can change the subsequent git command (in the example is git submodule update --init
) to others like git pull
, git fetch
, etc.