1つのサーバで複数のGitHub DeployKeyを切り替えて使う

公開日時

RaspberryPi上で動かしているアプリケーションが複数あり、それぞれのアプリケーションのデプロイ(git pull)用にdeploy keyを利用している。

GitHubの仕様上、一つのdeploy keyを複数アプリケーションで使い回すというのができないため、各アプリケーションごとにdeploy keyを作成する必要がある。

1つのサーバで複数のdeploy keyを使用する場合は一工夫必要だったので手順をまとめておく。

まずはdeploy keyの作成。

-fオプションでファイル名の指定ができる。

ssh-keygen -t rsa -b 4096 -C "" -f ~/.ssh/id_rsa_sample_app_deploy

生成したdeploy keyの公開鍵(~/.ssh/id_rsa_sample_app_deploy.pub)をGitHubのdeploy keyとして登録する。

その後、サーバの.ssh/configに各deploy keyを利用するHostの設定を追加する。

Host github-sample-app
  User git
  Port 22
  HostName github.com
  IdentityFile ~/.ssh/id_rsa_sample_app_deploy
  TCPKeepAlive yes
  IdentitiesOnly yes

Host github-sample-app2
  User git
  Port 22
  HostName github.com
  IdentityFile ~/.ssh/id_rsa_sample_app2_deploy
  TCPKeepAlive yes
  IdentitiesOnly yes

そして、アプリケーションのディレクトリに移動してoriginを変更する。

cd path/to/sample-app
git remote remove origin
git remote add origin git@github-sample-app:username/sample-app.git

これで今後はgit pull時にdeploy keyが認証情報として使用される。

deploy keyを使うことで、chatopsやデプロイの自動化がやりやすくなる。

参考


Related #raspberry pi