DEV Community

Valentin Berlin
Valentin Berlin

Posted on

Using multiple SSH-keys with git

Recently I found myself having to use two SSH keys on my machine to access code repositories hosted on Bitbucket under two different accounts, personal and work. In the end it was not very complicated, but it took me a while to figure out, so I decided to write everything down. :)

The first thing I need is to have both SSH keys on my machine. I already had the personal one, so I generated the second with same ssh-keygen terminal command. I had to give it a different file name though, to make sure my personal SSH key isn't overwritten. Once the key is created it should be added to the account that hosts the repositories (in my case Bitbucket account).

The next step is to create SSH configuration inside .ssh/config file. Each record in this file represents specific host (or hosts) and details a set of parameters to be used with it.
Every time the system is establishing SSH connection it will look through this config file and if the URI it is trying to connect to matches one of the Host records, it will use the parameters for this record. It supports many parameters, but I only needed two in this case.

The config is very simple:

  • when trying to connect to work.bitbucket.org connect to bitbucket.org instead and use credentials from id_rsa_work file.
  • in all other cases just use credentials from id_rsa file.
Host work.bitbucket.org
  HostName bitbucket.org
  IdentityFile ~/.ssh/id_rsa_work

Host *
  IdentityFile ~/.ssh/id_rsa

Enter fullscreen mode Exit fullscreen mode

Now the logical question here is where this work subdomain of bitbucket.org is coming from? When I try to git pull from either personal or work repos it goes to bitbucket.org. And the answer is that we can just fake it. Rather than use the real URL of the remote repository we can modify it.

All the parameters of a git repository are stored inside the .git/config file. We can print the repo's remote URL by executing git remote -v in the terminal. And to modify it we can either edit the config file directly or execute git remote set-url origin [new_url].

So to make the request of a particular repo to match our SSH configuration, we just need to prefix bitbucket.org in the repo's URL with work., e.g. git@work.bitbucket.org:valenber/myrepo.git.

This way when updating the repo (making pull or push) the system will try to establish SSH connection with work.bitbucket.org, it doesn't exist, but this request will never get further than our SSH config file, where it will get redirected to bitbucket.org and use the correct SSH key.

Top comments (0)