How to tell Git which SSH Key to use

Czar Pino
Czar Pino
Sep 10, 2017 · 1 min read

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 git@github.com:username/reponame.git. You would need to add a new host entry to your SSH config that uses the desired private key.

# ~/.ssh/config
Host 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 git@your.hostname.com: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 = git@your.hostname.com:username/reponame.git

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

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store