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
欢迎关注微信公众号,留言交流。

相关文章:

翻译: