Github同主機多倉庫部署deploy key問題處理

我的多個站點運行在同一個主機上,對應多個 github 私有倉庫,打包部署使用 deploy key,尷尬的是 github 限制每個倉庫必須用不同的 key,如果使用主機上面默認的那個 key,大部分時候會遇到錯誤提示:

1    ~ git clone [email protected]:kmephistoh/xxxx.git
2    Cloning into 'xxxx'...
3    ERROR: Repository not found.
4    fatal: Could not read from remote repository.
5
6    Please make sure you have the correct access rights
7    and the repository exists.

若要同一個主機使用 deploy key 部署多個倉庫

首先,創建多個 key

比如使用 ssh-keygen 創建多個密鑰對,把對應的公鑰(xxx.pub 的文件)放到 github 的 deploy key 中去,千萬不要說你找不到在哪裏啊……

 1    ➜  ssh-keygen
 2    Generating public/private rsa key pair.
 3    Enter file in which to save the key (/home/mephisto/.ssh/id_rsa): keyone
 4    Enter passphrase (empty for no passphrase):
 5    Enter same passphrase again:
 6    Your identification has been saved in keyone
 7    Your public key has been saved in keyone.pub
 8    The key fingerprint is:
 9    SHA256:EMDob/6SzsSOUGIdEqEUYLeSAIdJczUbl6HeLDUnthY mephisto@workpc
10    The key's randomart image is:
11    +---[RSA 3072]----+
12    |B@+=o=.oo        |
13    |B.B o *o         |
14    |.= o o.E .       |
15    |  = o =.*        |
16    |...o o =S        |
17    |.o .o o          |
18    |.  oo.           |
19    | . =+            |
20    |  ..+o.          |
21    +----[SHA256]-----+
22
23    ➜  ls -al keyone*
24    -rw------- 1 mephisto mephisto 2602 Nov  4 18:19 keyone
25    -rw-r--r-- 1 mephisto mephisto  569 Nov  4 18:19 keyone.pub

使用同樣方法創建另外一個 key,不操作演示了

其次,配置~/.ssh/config 文件

示例如下:

1    Host github.com-repo-1
2            Hostname github.com
3            IdentityFile=/home/user/.ssh/repo-1_deploy_key
4
5    Host github.com-repo-2
6            Hostname github.com
7            IdentityFile=/home/user/.ssh/repo-2_deploy_key
  • Host github.com-repo-1 # 倉庫別名(這個別名很關鍵)
  • Hostname github.com # github 域名
  • IdentityFile=/home/user/.ssh/repo-1_deploy_key # 倉庫使用的私鑰

最後,使用別名拉取代碼

注意,github.com-repo-1 就是上面的別名,仔細看,替換了@和:之間的字符串,不得不說 github 也是會玩。示例如下:

1    $ git clone [email protected]:OWNER/repo-1.git

這樣設置後,你就可以正常部署代碼了, 官方文檔https://docs.github.com/en/developers/overview/managing-deploy-keys

我想一個密鑰對走天下,怎麼辦?理論上可以把個人主力電腦的密鑰對放到服務器上面去,就像你在本地電腦操作一樣,但是這樣有安全風險,所以老實按照官方文檔處理,方便和安全總是有點矛盾,除非不在乎。

最後修改於: Thursday, October 26, 2023

相關文章:

翻譯: