Select private key to use with Git

If you are connecting via SSH then the key will be controlled by an SSH parameter, not a git parameter.

SSH looks in the ~/.ssh/config file for configuration parameters. Modify that file and add IdentityFile entries for the two Git servers like this:

Host server1.whatever.com
  IdentityFile /path/to/key_1
Host server2.whatever.com
  IdentityFile /path/to/key_2

This article has some more details.


There is another possibility. That's to set core.sshCommand, e.g.

git config --local core.sshCommand "/usr/bin/ssh -i /home/me/.ssh/id_rsa_foo"

There's one particular scenario when this strategy is particularly useful: that's when you have multiple accounts on Github, as all accounts ssh to Github as [email protected] and it uses the ssh key to determine which Github user you are. In this case neither .ssh/config nor ssh-agent will do what you want.

Update — You cannot run the above until you have a local repository, so if you're trying to clone a remote repository, you'll need to specify the key manually as per drewbie18's answer:

git clone -c core.sshCommand="/usr/bin/ssh -i /home/me/.ssh/id_rsa_foo" [email protected]:me/repo.git

Once you've cloned the repository you can use the git config command to set this permanently.


Generally, you want to use ~/.ssh/config for this. Simply pair server addresses with the keys you want to use for them as follows:

Host github.com
  IdentityFile ~/.ssh/id_rsa.github
Host heroku.com
  IdentityFile ~/.ssh/id_rsa.heroku
Host *
  IdentityFile ~/.ssh/id_rsa

Host * denotes any server, so I use it to set ~/.ssh/id_rsa as the default key to use.

Tags:

Git

Ssh