Gitで複数アカウントを使い分ける時の覚書
はじめに
参考記事
この記事は、個人の理解をまとめるものである。
また、この記事ではあえて冗長な書き方をしている。
前提
Gitのユーザー名、Gitの電子メールアドレス、ローカルリポジトリのパス、リモートリポジトリのアドレスはそれぞれ以下のようになるものとして書く。
環境に従って適宜読み換えたり書き換えること。
| Gitのユーザー名 | Gitの電子メールアドレス | ローカルリポジトリのパス | リモートリポジトリのSSH URL |
|---|---|---|---|
foo |
foo@example.com |
~/git/repository-foo |
git@git.example.com:foo/repository-foo.git |
bar |
bar@example.com |
~/git/repository-bar |
git@git.example.com:bar/repository-bar.git |
手順
以下の手順に従い作業を進める。
ssh接続の設定
初めにssh接続に関する設定を行う。
公開鍵・秘密鍵の生成
今回は両ユーザーとも~/.ssh内にssh接続に使用する公開鍵と秘密鍵を作る。
ssh-keygenを使う時にEnter file in which to save the keyみたいなことを言われるが、これは書き込むファイルの指定をフルパスで書けという指示である。デフォルトでは~/.ssh直下に作られる。
$ cd ~/.ssh
$ ssh-keygen -t ed25519 -C foo@example.com -f id_ed25519_git_foo
$ cd ~/.ssh
$ ssh-keygen -t ed25519 -C bar@example.com -f id_ed25519_git_bar
ssh-keygenのそれぞれのオプションの意味は以下の通りである。
| オプション | 意味 |
|---|---|
-t |
鍵の方式 |
-C |
コメント(慣習的に電子メールアドレスが使われる) |
-f |
鍵の名前 |
id_ed25519_git_fooやid_ed25519_git_barなど指定した名前そのものなファイルは秘密鍵、id_ed25519_git_foo.pubやid_ed25519_git_bar.pubのように末尾に.pubが付加されたものは公開鍵である。
余談)目的やユーザーごとにディレクトリを分ける。
目的やユーザーごとに~/.ssh内でディレクトリを分ける。
~/.ssh/git/fooと~/.ssh/git/barの内に公開鍵と秘密鍵を保存するなどでわかりやすくできる。
公開鍵をリモートサーバーに置く
各種サービスを利用する場合、それぞれの手段で各自設定すること。
~/.ssh/configの設定
参考記事
Host接続名はそれぞれgit_fooとgit_barとする。
Hostは[User]@[HostName]のように展開したものとして解釈される。具体例として、下記のgit_fooはgit@git.example.comと解釈される。
IdentityFileには秘密鍵のパスを指定する。
IdentitiesOnlyを指定することで、複数アカウントを利用する際に発生する問題を回避できる(らしい)。
TCPKeepAliveはssh接続のタイムアウトを防止する機能である。
Host git_foo
HostName git.example.com
User git
Port 22
IdentityFile ~/.ssh/id_ed25519_git_foo
IdentitiesOnly yes
TCPKeepAlive yes
Host git_bar
HostName git.example.com
User git
Port 22
IdentityFile ~/.ssh/id_ed25519_git_bar
IdentitiesOnly yes
TCPKeepAlive yes
gitの設定
この時、リモートリポジトリに設定するアドレスの一部を~/.ssh/configで設定したHost(例ではgit_fooやgit_bar)に書き換えること。
$ cd ~/git/repository-foo
$ git init
$ git config --local user.name foo
$ git config --local user.email foo@example.com
$ git remote add origin git_foo:foo/repository-foo.git
$ cd ~/git/repository-bar
$ git init
$ git config --local user.name bar
$ git config --local user.email bar@example.com
$ git remote add origin git_bar:bar/repository-bar.git
メインアカウントを指定する場合
メインアカウントにしたいユーザーのgit configを--globalで書けば良い。
今回はfooをメインアカウントとする場合の例を提示する。
$ git config --global user.name foo
$ git config --global user.email foo@example.com
Discussion