20
20

More than 5 years have passed since last update.

同一端末上でBitbucketの複数アカウントを使い分ける

Last updated at Posted at 2016-02-29

やりたいこと

Bitbucketには以下の制約があります(まぁ妥当な措置だと思います)

  • 同一のSSH公開鍵を複数のアカウントに登録できない

ただ、bitbucketで個人用と会社用のようにアカウントが複数あると管理がめんどくさくなります。
上記制約のせいでbitbucketに接続する際、1つのアカウントしか利用できなくなります。

できればリポジトリごとにSSH接続情報を切り替えながらやりたいものです。

ホスト名を偽装して接続を個別設定する

作業は2ステップです。

  1. ~/.ssh/configの接続設定をリポジトリ毎につくる
  2. リポジトリ毎にリモートのドメインを書き換える

1. ~/.ssh/configの接続設定をリポジトリ毎につくる

# Host repo1.bitbucket.orgの部分は区別できれば何でもいいです
$ vi ~/.ssh/config
===
Host repo1.bitbucket.org
  HostName        bitbucket.org
  User            git
  Port            22
  IdentityFile    ~/.ssh/id_rsa_repo1
  TCPKeepAlive    yes
  IdentitiesOnly  yes

Host repo2.bitbucket.org
  HostName        bitbucket.org
  User            git
  Port            22
  IdentityFile    ~/.ssh/id_rsa_repo2
  TCPKeepAlive    yes
  IdentitiesOnly  yes

2. リポジトリ毎にリモートのドメインを書き換える

# bitbucket.orgをrepo1.bitbucket.orgに書き換える
$ vi repo1/.git/config
===
[remote "origin"]
    url = git@repo1.bitbucket.org:<アカウント名>/repo1.git
===

# bitbucket.orgをrepo2.bitbucket.orgに書き換える
$ vi repo2/.git/config
===
[remote "origin"]
    url = git@repo2.bitbucket.org:<アカウント名>/repo2.git

解説

どのような流れで使われるかざっくり流れを追って説明します。

  1. (人間が) git push origin master実行する
  2. 対象リポジトリの.git/configからoriginの接続先ドメインを特定
  3. .ssh/configから対応するドメインのSSH接続情報を取得
  4. 指定されたSSH鍵を使ってbitbucketに接続
20
20
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
20