Running commands with sudo is a daily task for any system administrator, and Ansible makes it both repeatable and auditable. Instead of typing a command once per host, you define it once in a playbook and Ansible executes it everywhere, with the same privilege escalation rules. This guide walks you through the exact steps to run a sudo command using Ansible, from the simplest one-liner to handling passwords and become methods.
What You'll Need
- Ansible installed on your control node (the machine where you run
ansibleoransible-playbook). - At least one managed host (the target machine) reachable over SSH.
- SSH access to the managed host as a user that can use
sudo(typically a user withALL=(ALL) ALLin the sudoers file). - If you use a password for sudo, you need the
sshpasspackage (for password-based SSH) and the Ansiblebecome_passwordvariable set. - Basic familiarity with YAML syntax and Ansible inventory files.
Step-by-Step
1. Understand Ansible's Privilege Escalation
Ansible uses the become directive to switch to another user, typically root, via sudo. The key parameters are:
become: yes– enables privilege escalation.become_method: sudo– tells Ansible to usesudo(this is the default).become_user: root– the user you want to become (default isroot).become_flags– optional, to pass flags like-H(set HOME) or-E(preserve environment).
You can set these at the play level, the task level, or even in the inventory.
2. Create an Inventory File
Create a file named hosts.ini (or any name) with your managed host. For example:
[webservers]
web1.example.com
If your SSH user is not the default, specify it:
[webservers]
web1.example.com ansible_user=ubuntu
3. Write a Simple Playbook with a sudo Command
Create a file named sudo-command.yml. The simplest playbook that runs a command with sudo looks like this:
---
- name: Run a command with sudo
hosts: webservers
become: yes
tasks:
- name: Execute a command as root
command: whoami
Here, become: yes at the play level means every task in this play runs with sudo. The command module runs whoami, and because of become, it will print root.
4. Run the Playbook
Execute the playbook with:
ansible-playbook -i hosts.ini sudo-command.yml
If your SSH user requires a password, add -k (ask for SSH password). If sudo itself requires a password, add -K (ask for sudo password). If both, use both flags.
5. Run a Single Command with ad-hoc
You don't always need a playbook. For a one-off command, use the ansible command:
ansible webservers -i hosts.ini -m command -a 'whoami' --become
The --become flag enables sudo. To specify the become user, add --become-user=root. To ask for the sudo password, add --ask-become-pass.
6. Pass the sudo Password Automatically
If your sudo requires a password and you don't want to type it every time, you can store it in a variable. In the playbook, add:
vars:
ansible_become_password: "your_sudo_password"
Or better, use an Ansible Vault to encrypt the password. Create a vault file:
ansible-vault create secret.yml
Inside, put:
ansible_become_password: "your_sudo_password"
Then in the playbook, include the vault file:
vars_files:
- secret.yml
Run with --ask-vault-pass to unlock it.
7. Use become on a Single Task
Sometimes you only need sudo for one task. Put become: yes inside the task, not at the play level:
tasks:
- name: Update apt cache (needs root)
apt:
update_cache: yes
become: yes
8. Handle sudo Flags
If your sudo setup requires specific flags (like -H to set HOME), set become_flags:
become: yes
become_flags: '-H'
9. Run a Shell Command with sudo (using shell module)
If you need shell features like pipes or redirection, use the shell module instead of command:
tasks:
- name: Run a shell command as root
shell: "echo 'root' | tee /tmp/root.txt"
become: yes
10. Test with --check and --diff
Before running, test your playbook with --check to see what would change, and --diff to see file changes. For commands, --check may not work perfectly (since commands are not idempotent by default), but it's still useful for validation.
Common Mistakes
- Forgetting to set
become: yes– The most common mistake. Without it, the command runs as the SSH user, not root. - Using
sudoinside the command – Do not writecommand: sudo whoami. Ansible'sbecomealready handles sudo; addingsudoin the command can cause issues with password prompts and is redundant. - Hardcoding passwords in playbooks – This is insecure. Use Ansible Vault or environment variables.
- Not specifying
become_userwhen needed – If you need to become a non-root user, likewww-data, you must set it. - Using
commandinstead ofshellfor complex commands – Thecommandmodule does not support pipes, redirection, or variables. Useshellfor those.
Tips
- Prefer modules over raw commands – For common tasks like package installation or file management, use the dedicated modules (
apt,yum,copy,file) instead of raw shell commands. They are idempotent and handle error checking better. - Use
becomeat the play level for consistency – If most tasks need root, set it once at the play level to avoid repetition. - Store become password in a variable – Use
ansible_become_passwordin group_vars or host_vars, encrypted with Vault. - Test with a single host first – Use
--limitto run on one host before rolling out to all. - Use
--syntax-checkto validate your playbook – Catches YAML errors before execution.
Troubleshooting
- “Missing sudo password” error – This means your sudo requires a password and Ansible doesn't have it. Add
-Kto the command line, or setansible_become_passwordin your playbook or inventory. - “sudo: a password is required” – Same as above, but often because the SSH user is not in the sudoers file with NOPASSWD. Either add the user to sudoers with NOPASSWD (if acceptable) or provide the password.
- “Permission denied” even with become – Check that
become_methodis set tosudo(it is by default). Also verify that thebecome_userexists and has the right permissions. - Command runs but output is not as expected – Use
-v(verbose) to see the actual command executed. Sometimes the shell's environment differs (e.g., PATH). Usebecome_flags: '-H'to set HOME, or specify full paths. - Playbook hangs on password prompt – If you see a prompt for a password but you're running non-interactively (e.g., from cron), you must supply the password via a variable or use SSH keys with NOPASSWD sudo.
- SSH connection fails – Ensure the SSH user has permission to connect, and that SSH keys are set up. Test with
ssh user@hostmanually.
Frequently Asked Questions
Can I run a sudo command without a playbook?
Yes, use the ad-hoc ansible command with --become as shown in Step 5.
How do I run a command as a specific user other than root?
Set become_user to that user. For example, become_user: www-data.
What is the difference between become and sudo in Ansible?
become is Ansible's abstraction for privilege escalation, and sudo is one method (others include su, pfexec, etc.). You set become_method: sudo to use sudo specifically.
Is it safe to store sudo passwords in Ansible?
It is safe if you encrypt them with Ansible Vault. Never store them in plain text in playbooks or inventory files.
Why does my command module not support pipes?
The command module runs the command directly without a shell, so shell features are not available. Use the shell module for that.
Can I use become with Windows hosts?
Yes, but the method is different (e.g., runas). For Windows, you typically use become_method: runas and specify become_user as an administrator. The steps above are for Unix-like systems.