Home > Software engineering >  How to switch between SSH keys to use in a github account
How to switch between SSH keys to use in a github account

Time:10-21

I have two SSH keys. One is for my company github account and the other one is for my personal github account. My company account SSH key had been working well before I created another SSH key for my personal account. The last SSH key pair I created was for my personal account and it worked well. Now, I am trying to push to my company account but I get an error message. Is there some way to use both SSH keys or to switch between them ? I will share my config file. The first one is the original SSH key for my company account.

Host *
  AddKeysToAgent yes
  UseKeychain yes
  IdentityFile ~/.ssh/id_rsa

Host github.com
  HostName github.com
  AddKeysToAgent yes
  UseKeychain yes
  IdentityFile ~/.ssh/id_ed25519
  IdentitiesOnly yes

    

CodePudding user response:

The Git FAQ covers this topic thoroughly, both for SSH and for HTTPS. For SSH, the FAQ suggests the following in your ~/.ssh/config:

# This is the account for author on git.example.org.
Host example_author
    HostName git.example.org
    User git
    # This is the key pair registered for author with git.example.org.
    IdentityFile ~/.ssh/id_author
    IdentitiesOnly yes
# This is the account for committer on git.example.org.
Host example_committer
    HostName git.example.org
    User git
    # This is the key pair registered for committer with git.example.org.
    IdentityFile ~/.ssh/id_committer
    IdentitiesOnly yes

It then notes that you'll need to change your URLs:

Then, you can adjust your push URL to use git@example_author or git@example_committer instead of [email protected] (e.g., git remote set-url git@example_author:org1/project1.git).

Obviously in your case, you'll want to use github.com in place of git.example.org and you'll probably want to use different entries for the hostnames.

  • Related