Skip to content

Instantly share code, notes, and snippets.

@kendallroth
Last active August 28, 2017 17:33
Show Gist options
  • Save kendallroth/f78fbe0b766646f819193093d8079d94 to your computer and use it in GitHub Desktop.
Save kendallroth/f78fbe0b766646f819193093d8079d94 to your computer and use it in GitHub Desktop.
Manage multiple SSH keys and Git accounts

Managing multiple SSH keys and Git accounts

It can sometimes be useful to have multiple SSH keys for the same Git hosts, which requires some additional SSH configuration.

Example

A typical example involves using the same host (GitHub) with multiple accounts on the same computer. Since each account should use its own SSH key, we need to use a combination of the SSH configuration and Git remotes to determine which SSH key to use.

Configuration

1. Generate a unique SSH key for each use case

SSH keys should follow the following naming format: [Host]-[Use] (ie. github-personal).

  • Host - Host the key will be associated with
    • ie. github for GitHub repositories
  • Use - What kind of work the key will be used for
    • ie. personal for personal work
~/.ssh/
  id_rsa.github-personal
  id_rsa.github-personal.pub

Keys can be generated using the following command: ssh-keygen -t rsa -C "[EMAIL_ADDRESS]" -b 4096

Add the key to the ssh agent:

eval $(ssh-agent -s)
ssh-add ~/.ssh/other_id_rsa

2. Modify your SSH config file (typically ~/.ssh/config) with the required hosts and identity files

The SSH config file is typically located at ~/.ssh/config.

  • Host - Host name for referencing later (in Git config)
  • HostName - Actual host name
  • User - User who will be using the credentials
  • IdentityFile - SSH private key file
  • IdentitiesOnly - Prevents falling back to the default key
# ~/.ssh/config

Host github-personal
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_rsa.github-personal
  IdentitiesOnly yes

Host github-work
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_rsa.github-work
  IdentitiesOnly yes

3. Modify the Git remote urls

The new SSh configuration will be used when attempting to connect to a Git remote, meaning that if the Git remote URL is updated to match the configuration's Host parameter it will use the nested information.

remote["origin"]
  git@github-personal:username/repository.git

4. Add the SSH Key to Remote

SSH keys should follow the following naming format when added to the remote: [Host]-[Use]-[Location] (ie. github-personal-macbook).

  • Host - Host the key will be associated with
    • ie. github for GitHub repositories
  • Use - What kind of work the key will be used for
    • ie. personal for personal work
  • Location - Physical location of the key (one place only)
    • ie. macbook for key created on a MacBook
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment