Understanding Privilege Escalation in Ansible Playbooks
Privilege Escalation in Ansible
Ansible, by default, executes tasks with the privileges of the user account that is running the Ansible command. However, many administrative tasks require elevated privileges, such as root or sudo access, to perform actions like installing software, modifying system configurations, or managing user accounts.
To address this requirement, Ansible provides the become
keyword, which allows you to escalate the privileges of a task to a different user, typically the root user or a user with sudo permissions.
Become Keyword in Ansible
The become
keyword in Ansible is used to specify the user account under which a task should be executed. This can be set at the playbook level, the task level, or even the host level, depending on your specific requirements.
When you use the become
keyword, Ansible will attempt to escalate the privileges of the task to the specified user account. This can be done using various methods, such as sudo
, su
, or enable
(for network devices).
- hosts: all
become: true
tasks:
- name: Install package
apt:
name: nginx
state: present
become: true
In the example above, the become
keyword is used at both the playbook level and the task level to ensure that the "Install package" task is executed with elevated privileges.
Become Options
Ansible provides several options to configure the become
behavior, such as:
become_user
: The user account to switch to when executing the task.
become_method
: The privilege escalation method to use (e.g., sudo
, su
, enable
).
become_flags
: Additional flags to pass to the privilege escalation method.
These options can be set at the playbook, task, or host level to fine-tune the privilege escalation process.
- hosts: all
become: true
become_method: sudo
become_user: root
tasks:
- name: Install package
apt:
name: nginx
state: present
In this example, the become_method
is set to sudo
, and the become_user
is set to root
, ensuring that the "Install package" task is executed with root privileges.