Using ssh keys with Github and Bitbucket with multiple accounts

Both Github and Bitbucket recently changed the way developers must access their repositories when cloning, pushing or pulling. For both, ssh keys would seem like a good solution, but if you’ve got multiple accounts with either service, that can be tricky. The solution is fairly simply, though.

The solution is identical for both Github and Bitbucket, so I’ll use Bitbucket in the examples.

Create a public/private keypair for the first account

ssh-keygen 

Give the file a unique name (e.g.: bitbucket_personal_rsa), and save it in your .ssh folder.

Open the .pub version of the file (bitbucket_personal_rsa.pub), go to Bitbucket, and add it as one of your keys.

Add the new identity file to your .ssh/config file

Host me
    HostName bitbucket.org
    IdentityFile ~/.ssh/bitbucket_personal_rsa
    User git

The trick here is that the value after Host is an alias that references the current identity block and the Hostname on the next line. You can use that alias when executing git from the shell:

git clone git@me:username/myrepo.git

Or, if you need to add an origin:

git remote add origin git@me:username/myrepo.git

Add other keys to other accounts as required

And make sure to add them to your .ssh/config file with a suitable alias:

Host me
    HostName bitbucket.org
    IdentityFile ~/.ssh/bitbucket_personal_rsa
    User git

Host work
    HostName bitbucket.org
    IdentityFile ~/.ssh/bitbucket_work_rsa
    User git

Conclusion

Hope that helps. I had a couple of weeks of pulling my hair out trying to juggle accounts on these services. The above approach solved all my issues.