Skip to content

GitHub Deploy Key を複数登録してgit cloneする方法

Posted on:2019年3月19日 at 00:00

概要

GitHub のリポジトリに Deploy Key を登録は前回の記事で行ったが、 複数のリポジトリから git clone をする場合、すでに登録した Deploy Key は GitHub ではエラーで登録できない。 その場合、2つの選択肢がある。

  1. 別の Deploy Key の登録
  2. デプロイ専用のユーザアカウントの作成

今回は 1.の “別の Deploy Key の登録” の方法を残しておく。 リポジトリごとに別々の鍵を登録するので、ssh config を利用して使用する鍵を指定する方法となる。

使用バージョン

Datapipeline に使う SSH の鍵 Deploy Key の追加

ssh 鍵の作成

ssh-keygen -t ed25519 -a 100 -C '[email protected]' -f deploy_key.id_ed25519
ssh-keygen -t ed25519 -a 100 -C '[email protected]' -f another_deploy_key.id_ed25519
cat deploy_key.id_ed25519
-----BEGIN OPENSSH PRIVATE KEY-----
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
-----END OPENSSH PRIVATE KEY-----

cat deploy_key.id_ed25519.pub
ssh-ed25519 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx [email protected]
cat another_deploy_key.id_ed25519
-----BEGIN OPENSSH PRIVATE KEY-----
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
-----END OPENSSH PRIVATE KEY-----

cat another_deploy_key.id_ed25519.pub
ssh-ed25519 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx [email protected]

clone したリポジトリに Deploy Key の登録

.pub 公開鍵をリポジトリの Deploy Key に登録

Datapipeline で鍵の登録

echo -n "-----BEGIN OPENSSH PRIVATE KEY-----
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
-----END OPENSSH PRIVATE KEY-----
" > ~/.ssh/deploy.id_ed25519
chmod 600 ~/.ssh/deploy.id_ed25519

それぞれのリポジトリに登録した鍵を IdentityFile に指定する。 Host で書いてる “repo” “another_repo” は任意の名前で良い。

echo -n "
Host repo
  HostName github.com
  User git
  Port 22
  IdentityFile ~/.ssh/deploy_key.id_ed25519
  TCPKeepAlive yes
  IdentitiesOnly yes

Host another_repo
  HostName github.com
  User git
  Port 22
  IdentityFile ~/.ssh/another_deploy_key.id_ed25519
  TCPKeepAlive yes
  IdentitiesOnly yes
" >> ~/.ssh/config
chmod 600 ~/.ssh/config

git clone

ssh/config で設定した Host 名を本来 github.com がくる位置に差し替えておく git clone git+ssh://git@{Host}/repo.git

今回の例でいうと下記のようになる。

git clone git+ssh://git@repo/repo.git
git clone git+ssh://git@another_repo/repo.git

これの応用すれば、3 個でも 10 個でもリポジトリに Deploy Key を登録すればプライベートリポジトリを追加できるが、管理が煩雑になるので 3 個以上ならデプロイ用のユーザを作ったほうが良さそうだ。

参考