Git - Set SSH private key per repository

Git - Set SSH private key per repository

I work with git repositories from multiple sources - GitHub, GitLab, and Enterprise GitHub instance. I have a separate SSH keys for each of them and further, I have to keep track of other SSH keys that I use for accessing servers and other resources.

Recently, I got a new Windows machine from work and it started complaining that it couldn't use the right SSH key for my Enterprise GitHub repositories. No matter what I tried, it failed to authenticate correctly.

While, searching for a solution, I came across two ways to solve this:

Git config

Git provides a config parameter (git >v2.10) that can override the ssh command that git uses. So, piggybacking on this command, we can pass in the identity file information to it.

git config core.sshCommand "ssh -i ~/.ssh/id_rsa_github -F /dev/null"

What this enables is the ability to set a different SSH key for each repository as needed. Further, this method works across platforms.

Environment variable

Another method is to use the GIT_SSH_COMMAND (git >v2.30) environment variable to do the same. You can add an alias for git based on the site.

alias github='GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa_github -F /dev/null" git'

And then use github clone repo_url instead of git clone repo_url.

I prefer using the git config method as I don't have to worry about which alias to use in which repository.