Privilege escalation in Ansible refers to the process of increasing the level of permissions on a remote host in order to execute tasks that require elevated permissions.
This can be accomplished in Ansible by specifying the appropriate become method and become user in the playbook or task.
There are several become methods available in Ansible:
sudo
: Allows a user to execute a command with elevated privileges. This is the default become method used by Ansible.su
: Allows a user to switch to a different user account before executing a command.pbrun
: Allows a user to execute a command with elevated privileges using the PowerBroker Run utility.doas
: Allows a user to execute a command with elevated privileges using the OpenBSD doas utility.
Example 1:
---
- name: Example playbook with privilege escalation
hosts: all
become: true
become_method: sudo
tasks:
- name: Install Apache web server
apt:
name: apache2
state: present
In this example, the become
and become_method
options are used to enable privilege escalation using the sudo
method. The apt
module is then used to install the Apache web server on all hosts in the inventory.
Example 2:
---
- name: Example playbook with privilege escalation using su
hosts: all
become: true
become_method: su
become_user: root
tasks:
- name: Create directory with root ownership
file:
path: /opt/app
state: directory
owner: root
group: root
mode: '0755'
In this example, the su
method is used to switch to the root user before creating a directory with root ownership and permissions using the file
module.
Privilege escalation can also be used conditionally based on certain criteria, such as the operating system or the presence of a certain package.
Here is an example that installs a package using sudo
on Debian-based systems and su
on Red Hat-based systems:
---
- name: Example playbook with conditional privilege escalation
hosts: all
tasks:
- name: Install package
apt:
name: nginx
state: present
when: ansible_distribution == 'Debian'
become: true
become_method: sudo
- name: Install package
yum:
name: nginx
state: present
when: ansible_distribution == 'RedHat'
become: true
become_method: su
become_user: root
In this example, the when
condition is used to check the operating system before executing the appropriate package installation task with the correct privilege escalation method.