gitgithubsshconfigssh-config

How to specify several IdentityFile in .ssh/config for same host


In documentation about IdentityFile it says:

It is possible to have multiple identity files specified in configuration files; all these identities will be tried in sequence. Multiple IdentityFile directives will add to the list of identities tried (this behaviour differs from that of other configuration directives)

At this moment my config file look like:

# Default GitHub
Host github.com
  HostName github.com
  User git
  IdentityFile full\path\to\private\key\1

# Work GitHub
Host github-work.com
  HostName github.com
  User git
  IdentityFile full\path\to\private\key\2

And it works perfectly. I tried to combine them and tried to rewrite my config in this way:

# Default GitHub
Host github.com
  HostName github.com
  User git
  IdentityFile full\path\to\private\key\1
  IdentityFile full\path\to\private\key\2

And I expected that ssh will be able to automatically determine which file should it use to clone repository form GitHub. But the problem is when GitHub denied the access for first key it doesn't try to use second private key

When I tried to clone repository which belongs to first private key it works perfectly, also if I reorder the first and second private keys I will be able to clone repository which belongs to second private key

Is there any way to write private keys in any order and ssh will automatically determine which private key has access to given repository and give error only if none of private keys has access?

P.S. I'm working on Windows 10


Solution

  • From your first config we can see you have two different accounts at GitHub. Here is the problem: SSH knows nothing about Git or GitHub, and Git knows nothing about multitude of SSH keys.

    The process is as follows: you run a git clone command with an SSH URL; Git starts ssh to connect to the github.com host as git user; ssh connects and successfully authenticates by the 1st keypair; GitHub recognizes that it's a wrong user that doesn't have access to the repository so it rejects the request at the Git protocol level, not at SSH level and returns an error; there is no need for SSH to try another key — it was already connected; there is no way for Git to ask SSH to try another key (it doesn't know the keys exist) so Git aborts clone command.

    The bottom line: there is no way to do what you want with multiple GH accounts; continue using your first config, it's the way to go forever.