Sub topic 12
Managing keys with ~/.ssh/config
This chapter assumes you can generate an SSH key, add the public key to GitHub, and run ssh -T [email protected]. Here you will use the SSH config file to control which key SSH offers to which host.
Why a config file helps
Without a config file, SSH tries the default key files and any keys loaded in ssh-agent. If you have several keys, SSH offers them one after another. GitHub may reject the connection after a few failed offers, or it may accept a key that belongs to the wrong account.
The file ~/.ssh/config lets you name a host and pin a key to it. SSH reads it on every connection, so Git picks up the settings with no extra work.
A basic entry
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519
IdentitiesOnly yesEach line does one job:
Hostis the name you type on the command line or in a remote URL. SSH matches it against the entry.HostNameis the real server to contact.User gitis the account name GitHub expects for all SSH connections.IdentityFileis the private key to offer.IdentitiesOnly yestells SSH to offer only the key named here. It ignores every other key in ssh-agent.
Set the permissions so only you can read the file:
chmod 600 ~/.ssh/configUsing two accounts with aliases
Suppose you have a personal and a work GitHub account, each with its own key. Both use github.com, so Host github.com can match only one key. The fix is an alias. The Host name can be any label, and HostName holds the real server.
Host github-personal
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519_personal
IdentitiesOnly yes
Host github-work
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519_work
IdentitiesOnly yesNow point each repository's remote at the alias instead of github.com:
git remote set-url origin git@github-work:OWNER/REPO.git
ssh -T git@github-workThe second command should greet you with the work account's username. If it shows the personal username, SSH offered the wrong key.
Common mistakes
- Leaving out
IdentitiesOnly yes. SSH may still offer other keys from ssh-agent first, and GitHub then authenticates you as the wrong account. - Using a wrong path in
IdentityFile. SSH skips a missing file without an error, so the symptom is onlyPermission denied (publickey). - Putting a general
Host *block before specific ones. SSH uses the first value it finds for each option, so order specific hosts first. - Using
~/.ssh/id_ed25519.pubas theIdentityFile. Name the private key, not the.pubfile.
Exercise
You have two keys and two remotes that both use [email protected]. Every push authenticates as your personal account, even for work repositories. What two changes fix this?
Show answer
Create separate Host aliases in ~/.ssh/config, each with its own IdentityFile and IdentitiesOnly yes. Then change the work repository's remote with git remote set-url so it uses the alias, such as git@github-work:OWNER/REPO.git.