gitgogithubssh-keysgo-get

How can you specify which ssh key `go get` will use


I'm using two different github accounts (personal and work) on the same laptop (running Ubuntu version 20). I need to be able to access private repos from work using the ssh key for my work github account.

I've made it all work using some neat git config controls, i.e. in my ~/.gitconfig file I've put:

[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

The personal config contains:

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

The work config contains:

[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

This all works great for pulling and pushing from github (and signing work commits with a gpg key), but it is failing for go get on private repos. For some bizarre reason go get is trying to use my personal ssh key (~/.ssh/id_rsa) instead of my work ssh key (~/.ssh/id_ecdsa). I've set the GOPRIVATE environment variable, i.e.

export GOPRIVATE=github.com/work_account/*

The output of go get is like:

$ 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.

I can see that my ssh agent has both keys:

$ 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)

When I remove my personal ssh key (i.e. rm ~/.ssh/id_rsa*) then go get works just fine on the private repo, so I know it is definitely just trying to use the wrong ssh key. For some reason it is ignoring the git config core.sshCommand.


Solution

  • After a lot of trial and error and digging around, I've found a solution. If I set the environment variable GIT_SSH_COMMAND="ssh -i ~/.ssh/id_ecdsa" in the private repo then go get uses the correct ssh key and then works for private repos. It seems that go get ignores the git config core.sshCommand but is taking into account the environment variable GIT_SSH_COMMAND.

    To simplify my life I've used the program direnv to set this environment variable in the folder I keep my work repos in. The .envrc file in the top level folder looks like this:

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