Railway gun

Web系企業に勤めるサラリーマンが書くブログ

BitbucketのSSH接続エラー

みんな大好きBitbucketは自分も愛用しているのですが、
今までpushする際にはSSHではなくHTTPS経由でpushしていました。
SSH経由に変えようとしたところ、アホみたいなミスでpushエラーが起きまくったので記載。

発生したエラー

要するに「あなたの登録した鍵ではアクセスできませんよ!」というエラー。

$ git push -u origin --all
ermission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

状況(やったこと兼手順)

Macで以下の手順を実施。途中の鍵コピー以外はCentOSなどでも同じはず。

SSHキーを作成。
$ ssh-keygen -f ~/.ssh/bitbucket -t rsa -C hoge@hoge.com
Bitbucketに鍵を登録。

鍵をコピーする。(Mac以外の方は手動でコピーすれば良いです。)

$ cat ~/.ssh/bitbucket.pub | pbcopy

で、Bitbucketのアカウントの管理>SSHキーから公開鍵を登録。

SSHのconfigを設定

エディタでSSHのコンフィグにBitbucket宛の設定を記載する。
(注:ここが間違っています。正解を見たい方は一番下をご覧ください。)

Host bitbucket
  HostName bitbucket.org
  IdentityFile ~/.ssh/bitbucket
  User git
BitbucketにSSHでアクセス。

まずはSSHコマンドでアクセス。普通に成功する。

$ ssh -T git@bitbucket
logged in as hogehoge.

You can use git or hg to connect to Bitbucket. Shell access is disabled.
リポジトリディレクトリに異動し、push先を設定。
$ cd <リポジトリのディレクトリ>
$ git remote add origin git@bitbucket.org:<ユーザ名>/<リポジトリ名>.git
Bitbucketにgitリポジトリをpush。ここで失敗する。
$ git push -u origin --all
ermission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

原因

SSHのconfig設定におけるHostがgitコマンドにあっていなかった。

誤った設定

Host bitbucket
  HostName bitbucket.org
  IdentityFile ~/.ssh/bitbucket
  User git

正解

Host bitbucket.org
  HostName bitbucket.org
  IdentityFile ~/.ssh/bitbucket
  User git

SSHのみを使う時にはHostはわかりやすく、短い物を設定しますが、
gitコマンドで設定したremote先はbitbucket.orgを参照するため、
誤った設定では「そんなホストに対応した鍵はない」となってしまいます。

そのため、SSHでは成功していてもgitコマンドでは失敗、というわけでした。
SSH関連で手間取ることはないと慢心していたら、1時間ほど費やしてしまったのでメモ。