Sub topic 9
Loading keys into ssh-agent
This chapter assumes you have already generated an Ed25519 key pair with ssh-keygen and that you know the difference between the private key and the .pub public key. You also need a terminal on Linux, macOS, or Git Bash on Windows.
Why an agent exists
If you protect your private key with a passphrase, SSH must decrypt the key each time it connects. Without help, every git push, git pull, or git fetch over SSH would prompt for that passphrase.
ssh-agent is a background process that holds decrypted private keys in memory. SSH clients, including the one Git calls, ask the agent to sign the authentication challenge. The private key never leaves the agent, and you type the passphrase once, when you add the key.
Start the agent and add a key
Start the agent in your current shell and load the key:
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519The first command starts the agent and sets two environment variables, SSH_AUTH_SOCK and SSH_AGENT_PID, so SSH can find it. The eval is required because the agent prints those assignments and your shell must run them. The second command prompts for the passphrase and stores the decrypted key.
Check what the agent holds:
ssh-add -lThis lists the fingerprint of each loaded key. If it prints The agent has no identities., the agent is running but empty. If it prints Could not open a connection to your authentication agent, the agent is not running in this shell.
Common errors
- Agent not running in a new terminal. Each
eval "$(ssh-agent -s)"starts a separate agent that is tied to the shell where you ran it. A new terminal window does not see it. Many desktop systems and macOS start an agent for you at login. Checkecho $SSH_AUTH_SOCKbefore starting another one. - Wrong key path.
ssh-addexpects the private key, not the.pubfile. A message such asNo such file or directoryusually means a typo in the path. - Keys vanish after a restart. Agent memory is cleared when the agent stops or you reboot. You can reload with
ssh-add, or let your system do it, as the callout below describes.
To remove keys, run ssh-add -d ~/.ssh/id_ed25519 for one key or ssh-add -D for all of them.
Where this fits
Loading the key only makes it available locally. GitHub still has to know the matching public key, which is the next step. After that, you can test the whole chain with ssh -T.
Exercise
You open a new terminal tab, run git push over SSH, and are asked for your key passphrase again, even though you ran ssh-add earlier in a different tab. What most likely happened, and how can you confirm it?
Show answer
The earlier ssh-add loaded the key into an agent that belongs to the other tab's shell. The new tab has no SSH_AUTH_SOCK pointing to it, or it points to an agent with no keys. Run echo $SSH_AUTH_SOCK and ssh-add -l in the new tab to confirm. Fix it by starting or connecting to an agent and running ssh-add again, or by using AddKeysToAgent yes in ~/.ssh/config.