To run privileged tasks without resorting to passwordless-sudo (NOPASSWD),
you can use the libpam ssh_agent_auth module to authenticate based on SSH public
keys in a separate authorized keys file.
This module requires SSH connections to be made with the -A command line option, or the
ForwardAgent yes config option. You also need a local SSH agent running with the required key added.
I've presented this as an Ansible playbook + variables as it's a useful application and wasn't completely straight forward to get working. There's no requirement to use Ansible though.
In cases where a shared user account is used, this has the nice benefit of identifying the individual key used to authenticate privileged escalation:
sudo[4624]: pam_ssh_agent_auth: matching key found: file/command /etc/security/sudo_authorized_keys, line 2
sudo[4624]: pam_ssh_agent_auth: Found matching ED25519 key: SHA256:EWdJKhuDw199fJzAJM1Zc5E1PzhW9zHUMyLlTW+zivI
sudo[4624]: pam_ssh_agent_auth: Authenticated: `ubuntu' as `ubuntu' using /etc/security/sudo_authorized_keys
This hash can be mapped back to the public key in your sudo_authorized_keys file using:
$ ssh-keygen -l -f /etc/security/sudo_authorized_keys
256 SHA256:EWdJKhuDw199fJzAJM1Zc5E1PzhW9zHUMyLlTW+zivI john@example.com(ED25519)
-
This doesn't bypass the normal
sudoprerequisites: a user with the correct key still needs to be in the sudoers file (eg. added to the sudo group) -
The configuration here tries SSH agent authentication, then falls back to interactive password authentication
-
This doesn't seem to work with hardware-backed ed25519-sk keys at the time of writing (May 2026), but other SSH key types work correctly.