Skip to content

Alias the host, not the key

2 min read
#ssh#git#macos

Two GitHub accounts on one machine is the usual reason people go looking for this, and the usual answers are bad: per-repository core.sshCommand overrides, or a script that swaps id_ed25519 in and out of the agent.

Neither is necessary. ~/.ssh/config lets you invent a hostname that only exists on your machine and bind a key to it:

Host personal.github.com
  HostName github.com
  AddKeysToAgent yes
  UseKeychain yes
  User git
  IdentityFile ~/.ssh/id_ed25519

Host work.github.com
  HostName github.com
  AddKeysToAgent yes
  UseKeychain yes
  User git
  IdentityFile ~/.ssh/id_ed25519_work

Host is a label that means nothing outside this file. HostName is where the connection actually goes. So both entries reach github.com, and which key gets offered depends only on which fiction you typed.

Then the remote URL carries the choice:

git clone git@personal.github.com:username/repo.git

The key selection now lives in the URL, which lives in .git/config, which travels with the clone. Nothing to remember and nothing to switch.

On macOS, UseKeychain yes stores the passphrase in the keychain and AddKeysToAgent yes loads the key on first use, so you type the passphrase once ever rather than once per reboot.

When it doesn’t work, one flag tells you why:

ssh -vT git@personal.github.com

The verbose output names the config entry it matched and the key it offered. Almost every failure here is one of two things: the URL still points at plain github.com, or you added a second key to an account that already has the first one. GitHub rejects a key that’s registered to a different account with a message about repository access, which sends people looking at permissions when the problem is the key.

Read next