登录
首页 >  Golang >  Go问答

自定义 go get 使用的 SSH 密钥

来源:stackoverflow

时间:2024-02-19 11:09:23 288浏览 收藏

对于一个Golang开发者来说,牢固扎实的基础是十分重要的,golang学习网就来带大家一点点的掌握基础知识点。今天本篇文章带大家了解《自定义 go get 使用的 SSH 密钥》,主要介绍了,希望对大家的知识积累有所帮助,快点收藏起来吧,否则需要时就找不到了!

问题内容

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

我使用一些简洁的 git 配置控件使这一切正常工作,即在我放置的 ~/.gitconfig 文件中:

[url "[email protected]: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 = [email protected]
[core]
sshcommand = ssh -i ~/.ssh/id_rsa

工作配置包含:

[user]
name = your name
email = [email protected]
signingkey = 
[core]
sshcommand = ssh -i ~/.ssh/id_ecdsa
[commit]
gpgsign = true
[gpg]
program = gpg

这对于从 github 拉取和推送(并使用 gpg 密钥签署工作提交)非常有用,但对于私人存储库上的 go get 来说却失败了。由于某些奇怪的原因, go get 试图使用我的个人 ssh 密钥(~/.ssh/id_rsa)而不是我的工作 ssh 密钥(~/.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 代理有两个密钥:

$ ssh-add -l
521 SHA256:EKvhgg24_blah_bApjLSqX4J7l0 [email protected] (ECDSA)
4096 SHA256:r/qcO94F+ox_blah_JkTiVk+aERk [email protected] (RSA)

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


解决方案


经过大量的尝试、错误和挖掘,我找到了解决方案。如果我在私有存储库中设置环境变量 git_ssh_command="ssh -i ~/.ssh/id_ecdsa" ,则 go get 使用正确的 ssh 密钥,然后适用于私有存储库。看来 go get 忽略了 git config core.sshcommand 但正在考虑环境变量 git_ssh_command

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

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

您在 ~/.ssh/config 文件中需要它。如果不存在,则创建它。它指定每个主机使用的 ssh 密钥。您可以通过添加无效域来添加别名:

host gitlab.com
identityfile ~/.ssh/id_ed25519

host github.com
identityfile ~/.ssh/id_ed25519

host github.invalid
hostname github.com
identityfile ~/.ssh/id_rsa

然后每次使用 [email protected] 时,都使用正确的 ssh 密钥。

相关的是 ~/.gitconfig 的添加,它有助于导入私有存储库。它使用 ssh 获取这些主机的所有 git 操作:

[url "[email protected]:"]
        insteadof = https://github.com/
[url "[email protected]:"]
        insteadof = https://gitlab.com/

另请参阅环境变量 goprivate,其中列出了不使用代理的私有存储库。 Example

GOPRIVATE=*.corp.example.com,rsc.io/private

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《自定义 go get 使用的 SSH 密钥》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>