How to tell Git which SSH Key to use

It is not possible to tell Git which SSH credentials to use ? strictly speaking. But you can use SSH config to effectively achieve the same result.

Suppose you have a private key ~/.ssh/special_id_rsa and you are trying to clone the repository [email protected]:username/reponame.git. You would need to add a new host entry to your SSH config that uses the desired private key.

# ~/.ssh/configHost your.hostname.com Hostname github.com User git IdentityFile ~/.ssh/special_id_rsa

If the SSH config file ~/.ssh/config does not exist, simply create it and add the host info. You then clone the repository by replacing the repo url domain with the host defined in the SSH config.

git clone [email protected]:username/reponame.git

After successful clone,git fetch and git commit will automatically use the special_id_rsa private key to connect to the Git server.

For already existing repositories however, you will additionally need to modify the Git config file .git/config inside the project. The url of remote ?origin? must be changed to the host defined in ~/.ssh/config.

# .git/config[remote “origin”] url = [email protected]:username/reponame.git

Now you can ?tell? Git which SSH credentials to use through SSH config.

21