It can sometimes be useful to have multiple SSH keys for the same Git hosts, which requires some additional SSH configuration.
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.
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
- ie.
- Use - What kind of work the key will be used for
- ie.
personal
for personal work
- ie.
~/.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
The SSH config file is typically located at ~/.ssh/config
.
Host
- Host name for referencing later (in Git config)HostName
- Actual host nameUser
- User who will be using the credentialsIdentityFile
- SSH private key fileIdentitiesOnly
- 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
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
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
- ie.
- Use - What kind of work the key will be used for
- ie.
personal
for personal work
- ie.
- Location - Physical location of the key (one place only)
- ie.
macbook
for key created on a MacBook
- ie.