Set Up SSH Key Authentication
Goal
Log in to servers and Git hosts with a key pair instead of a password, with short host aliases, and then turn password logins off.
Prerequisites
- Password access to each server, one last time.
Steps
- Generate a key on your own machine (Ed25519 is short, fast and secure). Add a passphrase: the agent will remember it.
ssh-keygen -t ed25519 -C "homelab-key" - Load it into the agent (on macOS,
--apple-use-keychainkeeps the passphrase in the Keychain):eval "$(ssh-agent -s)" ssh-add ~/.ssh/id_ed25519 - Copy the public key to each server:
ssh-copy-id user@SERVER_IP - For GitHub or GitLab, paste the public key (
cat ~/.ssh/id_ed25519.pub, orpbcopy <on macOS) in your profile's SSH Keys settings, then test:ssh -T git@gitlab.com. - Add aliases in
~/.ssh/config:Host mynode HostName SERVER_IP User user - Once key logins work, disable password authentication on each server in
/etc/ssh/sshd_config.d/no-passwords.conf:
thenPasswordAuthentication nosudo systemctl reload ssh.
Verify
-
ssh mynodelogs in without a password prompt. -
ssh -o PubkeyAuthentication=no mynodeis refused once step 6 is done.
Troubleshooting
- Still asked for a password: check permissions on the server:
~/.sshmust be700andauthorized_keys600. Permission denied (publickey)on Git:ssh -vT git@gitlab.comshows which keys were offered.WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!after reinstalling a server: the new OS has new host keys. Remove the old entry withssh-keygen -R <ip>(andssh-keygen -R <hostname>if you also connect by name), then reconnect and check the fingerprint.- Ansible hangs or fails on the first connection to a rebuilt node: it is waiting at the host-key prompt. Connect once by hand with
ssh user@<ip>and accept the key, then run the playbook. - Ansible's
--ask-passerrors withsshpassmissing: password SSH from Ansible needssshpass(brew install sshpasson macOS). Or push the key once withssh-copy-id user@<ip>and drop--ask-pass.
References
- OpenSSH: ssh-keygen(1) - key types and options.
- GitLab Docs: Use SSH keys to communicate with GitLab - adding and testing a key.
- GitHub Docs: Connecting to GitHub with SSH - keys, agent and host fingerprints.
- Linux Administration MOC - hub for Linux notes.