Search code examples
sshgithubssh-keys

Multiple GitHub Accounts & SSH Config


I'm having some trouble getting two different SSH keys/GitHub accounts to play well together. I have the following setup:

Repos accessible from one account using [email protected]:accountname

Repos accessible from another account using [email protected]:anotheraccount

Each account has its own SSH key. Both SSH keys have been added and I have created a config file. I don't believe the config file is correct though. I'm not quite sure how to specify that repos accessed using [email protected]:accountname should use id_rsa and [email protected]:anotheraccount should use id_rsa_anotheraccount.


Solution

  • Andy Lester's response is accurate but I found an important extra step I needed to make to get this to work. In trying to get two profiles set up, one for personal and one for work, my ~/.ssh/config was roughly as follows:

    Host me.github.com
        HostName github.com
        PreferredAuthentications publickey
        IdentityFile ~/.ssh/me_rsa
    
    Host work.github.com
        HostName github.com
        PreferredAuthentications publickey
        IdentityFile ~/.ssh/work_rsa
    

    My work profile didn't take until I did a ssh-add ~/.ssh/work_rsa. After that connections to github used the correct profile. Previously they defaulted to the first public key.


    If you encounter problems, they are likely from using the wrong account. You can troubleshoot things from the command line with a command like this (use ssh -vvv for max verbosity):

    $ GIT_SSH_COMMAND='ssh -v' git pull --verbose
    

    For Could not open a connection to your authentication agent when using ssh-add,
    check https://stackoverflow.com/a/17695338/1760313

    For defaulted to the first public key, add IdentitiesOnly to the Host * section at the bottom of your ~/.ssh/config file. This tells ssh to only use specified identities rather than all unlocked keys in your agent.

    If your Host * section has an IdentityFile line, this will not work. Remove that line and add it to a new Host !work.github.com * secion.

    If you use ControlMaster and you try to use different Github accounts before the ControlPersist timeout expires, it will use the persisted connection, which may be for the other account. Change your ControlPath to include %k (the host key alias if specified, otherwise this is identical to %h, the hostname). If you prefer, you can limit this to just one Github account's path with e.g. ControlPath ~/.ssh/control-%C-2 solely in the Host work.github.com stanza.