Select private key to use with Git

I have 2 Git servers that require 2 different SSH keys.

git clone user1@server1:blahblahblah uses ~/.ssh/id_rsa, but I need to specify which key to use depending on the server I am connecting to.

What Git command-line parameter does this job? (I am running Linux.)


Solution 1:

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.

Solution 2:

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.

Solution 3:

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.

Solution 4:

In my scenario, similar to @Richard Smith scenario (whose solution, BTW, didn't work for me), I need to use different keys for the same server under different repositories.

The workaround for me was to set up the session correctly with the environment variable GIT_SSH_COMMAND, like so:

export GIT_SSH_COMMAND="ssh -o IdentitiesOnly=yes -i ~/.ssh/my-secret-identitiy"

Update:

Another thing to note here is that setting the environment variable correctly can be a hustle, so I'm using the command prompt modification facilities provided by things like Liquid Prompt or Fish Shell to hook into the shell and keep updating the environment variables according to the current directory and some rules. For example, all my personal projects that need to my personal SSH key with Gitlab are under ~/Documents/Projects/personal so when the shell hook runs pwd and finds that the current directory is under that path, it automatically sets the GIT_SSH_COMMAND variables as needed.