Multiple Bitbucket Cloud accounts with SSH authentication

December 7, 2021 

In Bitbucket usernames are unique across whole of Bitbucket. Moreover, the same SSH key can only be configured for one user. If you registered your Bitbucket account using a corporate email and used your primary SSH key with it, you're pretty much hosed if you then need to create another corporate Bitbucket account and wanted to use the same SSH key with it - that's just not going to happen. The solution to this dilemma is to create another SSH keypair and somehow make SSH, Git and Bitbucket co-operate. As the correct solution was not immediately obvious it is documented here.

The first step is to create a new SSH keypair:

$ ssh-keygen -t ed25519 -f ~/.ssh/john_company_b

NOTE: RSA key's won't work with Bitbucket.

Once you have the key add entries for all your Bitbucket accounts in ~/.ssh/config:

Host bitbucket.org-john_company_a
     HostName bitbucket.org
     User git
     IdentityFile ~/.ssh/john_company_a
     IdentitiesOnly yes

Host bitbucket.org-john_company_b
     HostName bitbucket.org
     User git
     IdentityFile ~/.ssh/john_company_b
     IdentitiesOnly yes

Now comes the important part: you need to change the remote URLs so that Git will know which of these Host sections to use for each Git repository.

To clone a repository from "Company A":

git clone [email protected]_company_a:company_a/some-repository.git

To clone a repository from "Company B":

git clone [email protected]_company_b:company_b/some-repository.git

If you tried to just use

git clone [email protected]:company_b/some-repository.git

you would get Forbidden unless Git happened to use the correct SSH key by default.

Samuli Seppänen
Samuli Seppänen
Author archive
menucross-circle