git - 如何指定 `go get` 将使用哪个 ssh key

标签 git go github ssh-keys go-get

我在同一台笔记本电脑(运行 Ubuntu 版本 20)上使用两个不同的 github 帐户(个人和工作)。我需要能够使用工作 github 帐户的 ssh key 从工作中访问私有(private)存储库。

我已经使用一些简洁的 git 配置控件使它全部工作,即在我的 ~/.gitconfig 文件中,我放了:

[url "git@github.com:work_account/"]
    insteadOf = https://github.com/work_account/
[includeIf "gitdir:~/src/github.com/personal_account/"]
    path=~/.gitconfig_personal
[includeIf "gitdir:~/src/github.com/work_account/"]
    path=~/.gitconfig_work

个人配置包含:

[user]
name = Your Name
email = your.name@gmail.com
[core]
sshCommand = ssh -i ~/.ssh/id_rsa

工作配置包含:

[user]
name = Your Name
email = your.name@work.com
signingkey = <ID of GPG key>
[core]
sshCommand = ssh -i ~/.ssh/id_ecdsa
[commit]
gpgsign = true
[gpg]
program = gpg

这一切都非常适合从 github 中 pull 和推送(并使用 gpg key 签署工作提交),但它在私有(private) repo 上失败了。由于某些奇怪的原因 go get 试图使用我的个人 ssh key (~/.ssh/id_rsa) 而不是我的工作 ssh key (~/.ssh/id_ecdsa).我已经设置了 GOPRIVATE 环境变量,即

export GOPRIVATE=github.com/work_account/*

go get 的输出是这样的:

$ go get github.com/work_account/private_repo
go get github.com/work_account/private_repo: module github.com/work_account/private_repo: git ls-remote -q origin in /home/marc/pkg/mod/cache/vcs/ff3efb332cb48232e5da90ff2073685cbdac4a86e3a47aa11663696f4943637a: exit status 128:
        ERROR: Repository not found.
        fatal: Could not read from remote repository.

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

我可以看到我的 ssh 代理有两个 key :

$ ssh-add -l
521 SHA256:EKvhgg24_blah_bApjLSqX4J7l0 your.name@work.com (ECDSA)
4096 SHA256:r/qcO94F+ox_blah_JkTiVk+aERk your.name@gmail.com (RSA)

当我删除我的个人 ssh key (即 rm ~/.ssh/id_rsa*)时,go get 在私有(private)仓库上工作得很好,所以我知道肯定只是试图使用错误的 ssh key 。由于某种原因,它忽略了 git config core.sshCommand

最佳答案

经过大量的反复试验和深入挖掘,我找到了解决方案。如果我在私有(private)仓库中设置环境变量 GIT_SSH_COMMAND="ssh -i ~/.ssh/id_ecdsa" 然后 go get 使用正确的 ssh key 然后为私有(private)工作 repo 。似乎 go get 忽略了 git config core.sshCommand 但正在考虑环境变量 GIT_SSH_COMMAND

为了简化我的生活,我使用程序 direnv 在我保存我的工作 repos 的文件夹中设置这个环境变量。顶部的 .envrc 文件级别文件夹如下所示:

export GIT_SSH_COMMAND="ssh -i ~/.ssh/id_ecdsa"

关于git - 如何指定 `go get` 将使用哪个 ssh key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65569280/

相关文章:

syntax - go lang 中的空函数名是什么意思?

git - 开放端口 9418 是否足以让 GitHub 客户端完全运行?

git - 如何破坏 Git 存储库?

git - 获取我过去 5 天在 git 中完成的所有提交

git - 为什么 Git 不允许我从备用远程查看分支?

ios - 我如何在从 github 下载的 xcode 中打开已经存在的项目?

git - 无法将文件夹 www 添加到 github 存储库

git - 在 merge 了精选提交的分支上 pull 请求

string - 如何从 Golang 中的字符串中修剪 "["字符

firebase - Golang基于Firebase token 的身份验证。 [必要的方法在Admin SDK for Golang中不可用]