Github同主机多仓库部署deploy key问题处理

我的多个站点运行在同一个主机上,对应多个github私有仓库,打包部署使用deploy key,尴尬的是github限制每个仓库必须用不同的key,如果使用主机上面默认的那个key,大部分时候会遇到错误提示:

~ git clone [email protected]:kmephistoh/xxxx.git
Cloning into 'xxxx'...
ERROR: Repository not found.
fatal: Could not read from remote repository.

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

若要同一个主机使用deploy key部署多个仓库

首先,创建多个key

比如使用ssh-keygen创建多个密钥对,把对应的公钥(xxx.pub的文件)放到github的deploy key中去,千万不要说你找不到在哪里啊……

➜  ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/mephisto/.ssh/id_rsa): keyone
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in keyone
Your public key has been saved in keyone.pub
The key fingerprint is:
SHA256:EMDob/6SzsSOUGIdEqEUYLeSAIdJczUbl6HeLDUnthY mephisto@workpc
The key's randomart image is:
+---[RSA 3072]----+
|B@+=o=.oo        |
|B.B o *o         |
|.= o o.E .       |
|  = o =.*        |
|...o o =S        |
|.o .o o          |
|.  oo.           |
| . =+            |
|  ..+o.          |
+----[SHA256]-----+

➜  ls -al keyone*
-rw------- 1 mephisto mephisto 2602 Nov  4 18:19 keyone
-rw-r--r-- 1 mephisto mephisto  569 Nov  4 18:19 keyone.pub

使用同样方法创建另外一个key,不操作演示了

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

示例如下:

Host github.com-repo-1
        Hostname github.com
        IdentityFile=/home/user/.ssh/repo-1_deploy_key

Host github.com-repo-2
        Hostname github.com
        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也是会玩。示例如下:

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

这样设置后,你就可以正常部署代码了, 官方文档https://docs.github.com/en/developers/overview/managing-deploy-keys

我想一个密钥对走天下,怎么办?理论上可以把个人主力电脑的密钥对放到服务器上面去,就像你在本地电脑操作一样,但是这样有安全风险,所以老实按照官方文档处理,方便和安全总是有点矛盾,除非不在乎。

最后修改于: Monday, August 28, 2023

相关文章:

翻译: