Managing different SSH keys with Git

Peter Nguyen
Peter Nguyen

If you happen to work with different repositories, you may want to authenticate with separate SSH keys that are applicable to their working context. For example,

  • you want a clear separation between personal and work projects — using a personal key for personal projects, and a work key for work projects
  • you use different SSH keys for your development and production environments

By default, SSH searches for the identity file (private key) located at ~/.ssh/identity (for protocol version 1), and ~/.ssh/id_rsa and ~/.ssh/id_dsa (for protocol version 2) to authenticate.

To support multiple keys across different repositories, we'll need to tell Git which key to use when authenticating via SSH. We can do this by overriding the local repository's ssh command by setting the core.sshCommand variable — https://git-scm.com/docs/git-config#Documentation/git-config.txt-coresshCommand

git config --local core.sshCommand "ssh -i ~/.ssh/personal_id_rsa"

Breaking it down:

  • ssh -i ~/.ssh/personal_id_rsa will execute ssh reading the identity file located at ~/.ssh/personal_id_rsa
  • git config --local core.sshCommand will set the core.sshCommand variable in your local Git repository's configuration and use the ssh command that's been provided