SSH – How to Tell Git Which Private Key to Use

authenticationgitprivate-keyssh

ssh has the -i option to tell which private key file to use when authenticating:

-i identity_file

    Selects a file from which
    the identity (private key) for RSA or DSA authentication is read. 
    The default is ~/.ssh/identity for protocol version 1,
    and ~/.ssh/id_rsa and ~/.ssh/id_dsa for protocol version 2. 
    Identity files may also be specified on a per-host basis
    in the configuration file.  It is possible to have multiple -i options
    (and multiple identities specified in configuration files).

Is there a similar way to tell git which private key file to use on a system with multiple private keys in the ~/.ssh directory?

Best Answer

In ~/.ssh/config, add:

Host github.com
 HostName github.com
 IdentityFile ~/.ssh/id_rsa_github

If the config file is new, you might need to do chmod 600 ~/.ssh/config

Now you can do git clone git@github.com:{ORG_NAME}/{REPO_NAME}.git

  • Where {ORG_NAME} is your GitHub user account (or organization account)'s GitHub URI name.
    • Note that there is a colon : after github.com instead of the slash / - as this is not a URI.
  • And {REPO_NAME} is your GitHub repo's URI name
  • For example, for the Linux kernel this would be git clone git@github.com:torvalds/linux.git).

NOTE: On Linux and macOS, verify that the permissions on your IdentityFile are 400. SSH will reject, in a not clearly explicit manner, SSH keys that are too readable. It will just look like a credential rejection. The solution, in this case, is:

chmod 400 ~/.ssh/id_rsa_github