Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use different SSH keys for different accounts on the same Git hosting

Tags:

git

ssh

bitbucket

This question would be simple if I ask it as a use case. I have two SSH keys on my computer

  1. personal_id_rsa
  2. company_id_rsa

And I have two different user accounts on bitbucket.org. One of them is my personal account and the other is my company account. I have N number of repositories on my PC as well. Some of them has to be linked with my personal account and some other repos with the company account. There is no repositories that has to be linked to both the accounts. I have set the Identityfile inside the ~/.ssh/config to something like below.

Host *.bitbucket.org
   IdentityFile ~/.ssh/company_id_rsa

And whenever I want to push something to my personal repos, I change the config file to something like below.

Host *.bitbucket.org
   IdentityFile ~/.ssh/personal_id_rsa

And now, it becomes quite an inconvenience to edit the file whenever I want to make a git push. I was just thinking if I could just pickup one of the keys on the fly, when I push, it would have been a lot easier. Is there any way to do so?

I came across this question which explains a similar use case, but that is not the exact use case here.

like image 300
C-- Avatar asked Dec 03 '13 14:12

C--


1 Answers

You can add two Bitbucket "accounts" in your ssh config file. Bitbucket has alternative ssh host listening on port 443 (For those who has blocked almost all ports (sic!)).

Host bitbucketCompany
    User git
    HostName altssh.bitbucket.org
    Port 443
    IdentityFile ~/.ssh/company_id_rsa

Host bitbucketWork
    User git
    HostName bitbucket.org
    Port 22
    IdentityFile ~/.ssh/personal_id_rsa

Then update your remotes in .git/config

Company projects

[remote "origin"]
    url = ssh://bitbucketCompany/username/repo.git

Personal projects

[remote "origin"]
    url = ssh://bitbucketPersonal/username/repo.git
like image 56
Adrian Krupa Avatar answered Sep 20 '22 21:09

Adrian Krupa