Enabling Passwordles Sudo in Ansible: Lessons from the Field

When working with Ansible in a new environment, I ran into a common but often frustrating issue: Ansible prompting for the sudo password on every run. This slows down automation and makes it difficult to run playbooks unattended. The solution seemed simple—configure passwordless sudo for the user—but getting there required some troubleshooting.
The Problem: Ansible Keeps Asking for a Sudo Password
By default, when Ansible runs tasks that require elevated privileges (e.g., installing packages or modifying system settings), it uses become: true
to switch to the root user. However, if the user running Ansible does not have passwordless sudo configured, Ansible will prompt for a sudo password on every execution.
Initially, we tried to configure Ansible to ignore SSH key verification and use password authentication instead of SSH keys. While disabling strict host key checking helped, it didn’t solve the core problem: sudo access still required a password.
Attempted Fixes That Didn’t Work
We tried multiple approaches to bypass the sudo password prompt:
- Setting
ansible_become_password
in inventory- This is not recommended because storing plaintext passwords in Ansible inventory files is a security risk.
- Adding
NOPASSWD
manually in/etc/sudoers
- While effective, this required manual intervention, which defeats the purpose of automation.
- Using SSH keys instead of passwords
- Since we were initially authenticating via passwords, SSH keys weren’t a viable option in this case.
Each of these approaches had trade-offs, but none fully solved the issue in a seamless, automated way.
The Working Solution: --ask-pass -K
Ultimately, the command that worked was:
ansible-playbook -i inventory enable-passwordless-sudo.yml --ask-pass -K
Why This Works:
--ask-pass
→ Prompts for the SSH password since password-based authentication was being used.-K
(or--ask-become-pass
) → Prompts for the sudo password so Ansible can elevate privileges.- Running a playbook (
enable-passwordless-sudo.yml
) that adds the correct NOPASSWD entry to sudoers allows the user to gain passwordless sudo permanently.
Once this playbook ran successfully, subsequent Ansible runs no longer required the sudo password, making automation fully functional.
Key Takeaways
- When using password authentication with Ansible, both SSH and sudo passwords may be required.
- If Ansible prompts for a sudo password, it means the user is not configured for passwordless sudo.
- Using
--ask-pass -K
allows Ansible to authenticate both for SSH and sudo, ensuring the necessary configuration changes can be made. - Once passwordless sudo is enabled, automation becomes seamless.
This is a classic case of troubleshooting automation itself, which often requires a mix of trial, error, and understanding how authentication flows work within a system.
Now, with passwordless sudo enabled, we can proceed with setting up the OpenSearch cluster without interruptions.