Understanding SSH Key Selection: Why -i Might Not Work as Expected #
When trying to reach the admin of my (this) blog at Prose.sh from a new computer I ran into some unexpected bahaviour.
Hen using ssh, I assumed that specifying a key with -i (or in ~/.ssh/config) is enough to ensure it's used. Nope. If you have other keys loaded in ssh-agent, SSH might ignore your specified key.
The Unexpected Behavior #
Imagine this scenario:
- You have a key already added to ssh-agent.
- You try to connect using a different key with -i:1ssh -i ~/.ssh/correct_key.pem user@host
- SSH fails to authenticate despite explicitly pointing to the right key.
- But when you add the key to ssh-agent, it suddenly works:1ssh-add ~/.ssh/correct_key.pem
When trying to authenticate https://pico.sh/ it does not fail per se. But instead of showing me my logged in user, it thinks that
I am somebody new (after all, the first id_rsa key I sent is new) and asks me to choose a username.
But why did this happen?
How SSH Selects Keys #
By default, SSH tries keys in this order:
- Keys already loaded in ssh-agent
- Keys specified in ~/.ssh/config(IdentityFile ~/.ssh/correct_key.pem)
- Keys provided via -i
If SSH-agent has a key that doesn't work, SSH may fail before trying the one from -i.
How to Ensure SSH Uses the Right Key #
To force SSH to use only the key you specify, use:
1ssh -i ~/.ssh/correct_key.pem -o IdentitiesOnly=yes user@host
Or, configure it in ~/.ssh/config:
1Host myserver
2    IdentityFile ~/.ssh/correct_key.pem
3    IdentitiesOnly yes
This ensures that SSH ignores any keys in ssh-agent and only tries the specified key.
Takeaways #
- SSH-agent keys take priority over manually specified keys.
- Using -ialone might not be enough if other keys are loaded.
- IdentitiesOnly yesensures SSH only uses your chosen key.