Search code examples
gitbitbucketssh-keys

How can I automatically connect to Bitbucket as different users for different repos?


I'm currently using Bitbucket for both work and personal projects. The problem is that I have two different Bitbucket users I log in as to access and commit to the repos I use for work and the repos I use for my personal projects.

I use one SSH key pair for the work repos and another SSH key pair for my personal repos. However, when I run the following command, I always see that I'm logged into Bitbucket under my work user:

ssh -vT git@bitbucket.com

As a result, I cannot push or pull from my personal Bitbucket repos from the command line. How can I set up my repos so that it automatically always pushes and pulls work repos as my work Bitbucket user and personal repos as my personal Bitbucket user? Thank you.


Solution

  • The way to do this is with the combination of the unqiue $HOME/.ssh/config file and the reponame/.git/config file found in a given git repo.

    Your $HOME/.ssh/config file would look like the following.

    username@hostname:~$ cat ~/.ssh/config
    Host bbmine
            HostName bitbucket.org
            User git
            IdentityFile /home/username/.ssh/id_rsamine
    
    Host bbwork
            HostName bitbucket.org
            User git
            IdentityFile /home/usermname/.ssh/id_rsawork
    

    In the file reponame/.git/config in your git repo you would place a remote section like the following:

    [remote "bbmineremote"]
            url = bbmine:bitbucketusername/reponame.git
            fetch = +refs/heads/*:refs/remotes/bitbucket/*
    

    You could then push and pull branches like

    git push bbmineremote master
    

    or

    git pull bbmineremote master
    

    You can confirm that you have set this up correctly by running the following ssh command

    username@hostname:~$ ssh bbmine
    PTY allocation request failed on channel 0
    logged in as bitbucketusername
    
    You can use git or hg to connect to Bitbucket. Shell access is disabled
    Connection to bitbucket.org closed.
    

    These Host sections in an .ssh/config file are kind of like aliases for anything that uses ssh, like git.