ssh ログインで ~/.ssh/id_ras が優先されるのを防ぐには

GitLab を開発用サーバーに入れて運用し始めたのですが ~/.ssh/config に接続用の秘密キーを指定しても ~/.ssh/id_ras を使って接続しょうとしエラーになり困っていました。

実用SSH 第2版―セキュアシェル徹底活用ガイド

GitHub風システム、GitLab は ssh 接続のgitコマンドからのアクセス時には、sshのキーを使いユーザーを管理しています。

もし1人のUnix(Mac)アカウントがGitLabに複数のユーザーを登録していて、ユーザーAの公開キーが ~/.ssh/id_ras に対応するもので、ユーザーBの 公開キーが ~/.ssh/id_ras_git の場合を考えてみましょう(各ユーザーのリポジトリーはユーザーだけがアクセス出来ます)。ユーザーBに対応するリポジトリーをアクセスする際に ~/.ssh/config に

Host user-b-repo
  Hostname gitlab.xxxx.com
  User git
  IdentityFile ~/.ssh/id_ras_git

と書き git clone git@user-b-repo:user-b/zzzz.git の様にアクセスすると認証エラーになってしまいます。
ssh に -v オプションを付けて user-b-repo をアクセスしてみると

% ssh -v user-b-repo
OpenSSH_5.9p1, OpenSSL 0.9.8y 5 Feb 2013
debug1: Reading configuration data /Users/aaaaaa/.ssh/config
debug1: Reading configuration data /etc/ssh_config
   ....
debug1: Connection established.
debug1: identity file /Users/aaaaaa/.ssh/id_ras_git type 1    ← ~/.ssh/id_ras_git が使われています
  ...
debug1: Authentications that can continue: publickey,password
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /Users/aaaaaa/.ssh/id_rsa       ← ここに注目
   ...

なぜか ~/.ssh/id_ras を使って接続しています。この際に GitLab は ユーザーA がアクセスしてきたと解釈し、ユーザーBのリポジトリーにはアクセス権がないのでエラーを返します。

ここ数日悩んでいたのですが、今日判りました。 ~/.ssh/config に IdentitiesOnly yesを追加すれば、指定した秘密キーのみが使われるのでした!


ということで ~/.ssh/config は以下の様に書きましょう

Host user-b-repo
  Hostname gitlab.xxxx.com
  User git
  IdentityFile ~/.ssh/id_ras_git
  IdentitiesOnly yes