GitHub for WindowsのGit Shellで、Herokuへpush時にPermission deniedエラーが出る

GitHub for WindowsのGit Shellを使ってHerokuへpushしようとしたところエラーが発生したため、対応した時のメモ。

環境

 

発生したエラー内容

Warning: Permanently added 'heroku.com,50.19.85.156' (RSA) to the list of known hosts.
Permission denied (publickey).
fatal: Could not read from remote repository.

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

 

対応

手元のSSHキーを確認

GitHub for Windowsでは、GitHub用のSSHキー(github_rsa.pub/github_rsa)が「%USERPROFILE%\.ssh」に自動的に生成されます。


GitHubSSHキーをHerokuと共有することも可能ですが、サービスごとに分けておいたほうが良いと考え、Heroku用のSSHキーを生成することにします。



SSHキーの生成

今回は「heroku_rsa」という名前で生成するため、以下の「」を自分のユーザーに置き換えて実行します。
途中でパスフレーズの入力を求められるので、入力しておきます。
なお、SSHキーの名称を省略した時は、id_rsaファイルができます。

ssh-keygen -t rsa -f /c/Users//.ssh/heroku_rsa
Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase):<パスフレーズを入力>
Enter same passphrase again:<パスフレーズを再入力>
Your identification has been saved in /c/Users//.ssh/heroku_rsa.
Your public key has been saved in /c/Users//.ssh/heroku_rsa.pub.
The key fingerprint is:
# fingerprint

SSH-KEYGEN (1)


その結果、「%USERPROFILE%\.ssh」に、以下の2つのファイルが作成されました。


なお、Windows環境変数を入れて実行しようとすると、エラーで生成できません。

ssh-keygen -t rsa -f %USERPROFILE%/.ssh/heroku_rsa
Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
open %USERPROFILE%/.ssh/heroku_rsa failed: No such file or directory.
Saving the key failed: %USERPROFILE%/.ssh/heroku_rsa.

 

HerokuにSSHキーをアップ

キーのパス名を入力しないと、手元のSSHキーを提案してくるので、先程生成したキーを入力します。

heroku keys:add
Found the following SSH public keys:
1) github_rsa.pub
2) heroku_rsa.pub

Which would you like to use with your Heroku account? 2
Uploading SSH public key C:/Users/think/.ssh/heroku_rsa.pub... done

 

ssh_configの修正

Herokuにアップする際のキーを指定していするため、ssh_configを修正します。
「.ssh/ssh_config」を修正するのをWebで見かけますが、GitHub for Windowsの場合、そのパスにssh_configがありません。
GitHub for Windowsの場合は、以下にssh_configがあります(「PortableGit_xxxx」は自分の環境に読み替え)。

%USERPROFILE%\AppData\Local\GitHub\PortableGit_xxxx\etc\ssh


すでにGitHubSSHに関する記載がありますが、Heroku分として以下の内容を追記します。

Host heroku.com
User git
port 22
Hostname heroku.com
IdentityFile ~/.ssh/heroku_rsa
TCPKeepAlive yes
IdentitiesOnly yes

 

HerokuへアプリをPushする

途中でパスフレーズが求められますが、先程SSHキーを生成した時に入力したパスフレーズを入力します。
あとは問題なくHerokuへのPushが成功するかと思います。

git push heroku master
Warning: Permanently added 'heroku.com,50.19.85.156' (RSA) to the list of knownhosts.
Enter passphrase for key '/c/Users//.ssh/heroku_rsa':
Fetching repository, done.
...