Using SSH Keys with Multiple BitBucket Accounts

I was using BitBucket the other day for a new client, but I wasn't able to use my standard BitBucket account (business reasons). I attempted to add my standard SSH key (id_rsa) to the new BitBucket account but SSH keys must be unique to the entire BitBucket system. I don't understand the reason for this uniqueness but there is a way around it using a rarely used SSH technique.

First you need to generate a new SSH key. You will name it something different than the default (id_rsa) because it will be used exclusively for the new BitBucket account.

$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/scott/.ssh/id_rsa): /Users/scott/.ssh/bitbucket-alt
Enter passphrase (empty for no passphrase):
Enter same passphrase again:

You need to then add a new ssh config for this specific bitbucket account. The key part is the Host keyword which is what you will be using to access BitBucket with the new account.

$ cat >> ~/.ssh/config << EOF
Host bitbucket-alt
  User altuser
  HostName bitbucket.org
  IdentityFile ~/.ssh/bitbucket-alt
EOF

Then when you want to clone a git repository do this:

$ git clone git@bitbucket-alt:altuser/repo.git

Notice that the hostname and the username were changed to the new user.

Testing the SSH Connection

You an easily test the SSH connection to both the old BitBucket account and the new account by doing the following:

$ ssh -T git@bitbucket.org
logged in as scott.
$ ssh -T git@bitbucket-alt
logged in as altuser.

Pretty cool, eh?

What about any existing Git repositories?

If you have an existing git repository that you want to convert to using the SSH version with the new set of SSH keys, edit your .git/config file and change it to the above Git URL.

before:
...
[remote "origin"]
url = git@bitbucket.org:altuser/other-repo.git

after:
...
[remote "origin"]
url = git@bitbucket-alt:altuser/other-repo.git