Step 1
Confirm the target account
Use the username delivered for the image. Locate its real home directory instead of assuming /home/ubuntu.
getent passwd <username>
id <username>Step 2
Install the public key safely
Create the directory as the target user, back up any existing key file, and append the complete public-key line only when it is not already present.
install -d -m 700 -o <username> -g <username> /home/<username>/.ssh
touch /home/<username>/.ssh/authorized_keys
cp -a /home/<username>/.ssh/authorized_keys /home/<username>/.ssh/authorized_keys.bak
PUBLIC_KEY='ssh-ed25519 AAAA... comment'
grep -qxF "$PUBLIC_KEY" /home/<username>/.ssh/authorized_keys || printf '%s\n' "$PUBLIC_KEY" >> /home/<username>/.ssh/authorized_keys
chown <username>:<username> /home/<username>/.ssh/authorized_keys
chmod 600 /home/<username>/.ssh/authorized_keysStep 3
Inspect effective SSH policy
Validate configuration before reload. Keep the existing session open until a second connection succeeds.
sshd -T | grep -E 'pubkeyauthentication|passwordauthentication|permitrootlogin|authorizedkeysfile'
sshd -t && systemctl reload sshStep 4
Check logs and firewall
Use recent authentication logs to distinguish a rejected key from networking or account policy.
journalctl -u ssh --since '15 minutes ago' --no-pager
ufw status verbose