Search code examples
gitgithubssh

Setting up multiple SSH key access to Github


I'm trying to configure a remote linux machine to access two distinct git accounts which I own. I keep getting authentication access manifesting in.

> git push
ERROR: Repository not found.
fatal: Could not read from remote repository.

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

Steps i've taken,

  1. Generated a two sets of ssh keys (call them key1 and key2)
  2. Generated a config file at ~/.ssh/config
  3. Edited that file
    1 # Default github account: key1
      2 Host github.com
      3    HostName github.com
      4    IdentityFile ~/.ssh/key1
      5    IdentitiesOnly yes
      6
      7 # Other github account: key2
      8 Host github-key2
      9    HostName github.com
     10    IdentityFile ~/.ssh/key2
     11    IdentitiesOnly yes
  1. Added the .pub version to my two git accounts under the user account settings/ssh keys.
  2. Added them on my VM with ssh-add ~/.ssh/key1

I'm unsure really where to go from here and what the next steps are for why this isn't working. I feel like there might be a step i'm missing.


Solution

  • tl;dr: Add the following entry to your ~/.ssh/config where $user is the GitHub username and $key is the private key specified for that user and defined in the setting for that GitHub user:

    Host github.com-$user
        Hostname github.com
        User git
        IdentityFile ~/.ssh/$key
        IdentitiesOnly yes
    

    Then, configure your git remote URL:

    git remote add origin [email protected]$user:$user/$repo
    

    Basically, I had a long-running SSH key for work/personal projects, then wanted to add a new key for unrelated side projects. I did all of the steps you outlined in your question, and still got the same error. Doing $ GIT_SSH_COMMAND='ssh -v' git fetch showed that git was passing my main user's private key first, and even though it was authenticating correctly as a valid key, that user of course had no permissions on the new user's private repositories.

    Relevant post: https://medium.com/@ordinary.yobi/multiple-ssh-keys-on-github-f75a372d5374