Introduction

Ansible, a cornerstone of modern automation, empowers system administrators with the tools to execute tasks efficiently across distributed environments. One of its notable features is “become,” which facilitates privilege escalation for specific tasks or playbooks. In this article, we’ll explore the various ways to use “become” effectively while adhering to best practices and security considerations.

Understanding Ansible’s “Become”

Privilege escalation allows executing commands or tasks with higher permissions, usually involving switching to a different user, most commonly the superuser (root). Ansible’s “become” feature serves as a pivotal mechanism for handling such elevated operations, enhancing the flexibility and security of automation.

  • Links

https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_privilege_escalation.html

Using Become Directives

You can control privilege escalation using play or task directives, connection variables, or command-line options. Multiple ways of specifying privilege escalation settings exist, and understanding their precedence is crucial.

  • become: true: Set this directive at the play or task level to activate privilege escalation. This signifies that the task will be executed with escalated privileges.
  • become_user: Specify the user with the desired privileges. Importantly, this is the user you “become” during task execution, not necessarily the user you initially login as. The default value is often set to “root.”
  • become_method: At the play or task level, override the default privilege escalation method in the ansible.cfg configuration file. This allows using specific privilege escalation plugins or methods tailored to your environment.
  • become_flags: This directive permits using specific flags for tasks or roles. This flexibility is helpful for customizing behavior, such as changing the user when the shell is set to “nologin.”

Putting “Become” into Practice

Let’s explore a few examples of how to use the “become” feature effectively:

1. Managing a System Service as a Non-Root User: To manage a system service that requires root privileges while connected as a non-root user, use the default value of become_user (root):

``yaml

— name: Ensure the httpd service is running

ansible.builtin.service:

name: httpd

state: started

become: true

`

2. Running a Command as a Specific User: To execute a command as a different user, specify the become_user parameter:

`yaml

— name: Run a command as the apache user

ansible.builtin.command: echo "Hello"

become: true

become_user: apache

`

3. Executing a Command as the “nobody” User: When dealing with the “nobody” user and the shell is set to “nologin,” you can adjust the behavior using become_flags:

``yaml

— name: Run a command as nobody

ansible.builtin.command: echo "Hello"

become: true

become_method: su

become_user: nobody

become_flags: ‘-s /b