When working with Ansible ad-hoc commands, you often need elevated privileges to perform system-level operations. The common approach is to use the --become (or -b) flag with --ask-become-pass, but some environments require the traditional sudo su - approach.
For basic sudo operations in Ansible 2.0.0.2, you would typically use:
ansible somehost -m command -a "cat /etc/passwd" -u someuser --become --ask-become-pass
To specifically emulate sudo su - behavior, you need to combine several parameters:
ansible somehost -m command -a "cat /etc/passwd" \
-u someuser --become --become-method=su \
--become-user=root --ask-become-pass
For frequent usage, consider adding these settings to your ansible.cfg:
[privilege_escalation]
become = True
become_method = su
become_user = root
become_ask_pass = True
Here are common scenarios with sudo su - equivalent commands:
# Install package
ansible webservers -m apt -a "name=nginx state=present" \
--become --become-method=su --ask-become-pass
# Restart service
ansible dbservers -m service -a "name=mysql state=restarted" \
--become --become-method=su
- Ensure the target user has proper sudo rights to execute
su - - Verify
/etc/sudoerscontains:someuser ALL=(ALL) NOPASSWD: /bin/su - - Check SELinux context if permissions seem correct but commands fail
When working with Ansible adhoc commands, you often need elevated privileges to perform system-level operations. The standard approach using --ask-sudo-pass works for simple sudo scenarios, but what if your environment requires switching to root via sudo su -?
In Ansible 2.0.0.2, you need to understand several mechanisms:
- The difference between simple sudo and
sudo su - - How Ansible handles privilege escalation
- The proper syntax for complex privilege escalation
For your specific case where sudo su - is required, use this approach:
ansible somehost -m shell -a "sudo su - -c 'cat /etc/passwd'" -u someuser --ask-sudo-pass
In newer Ansible versions, the recommended way is through the become system. For your version (2.0.0.2), you can try:
ansible somehost -m command -a "cat /etc/passwd" -u someuser --become --become-method=su --become-user=root --ask-become-pass
If you encounter problems, check:
- The remote user's sudoers configuration
- Password prompt timing (use
-vvvfor verbose output) - SSH connection settings
For complex operations requiring multiple commands as root:
ansible somehost -m shell -a "sudo su - -c 'command1 && command2 || command3'" -u someuser --ask-sudo-pass
Remember that using sudo su - provides full root access. Consider:
- Using more specific sudo privileges when possible
- Implementing proper logging
- Restricting such access to only necessary hosts