Ansible Become
Using Ansible, you can perform various operations on remote machines using Ansible playbooks. By default, an Ansible playbook is executed on the remote host as the same user on the Ansible controller. That means if you want to run a command as another user on the remote machine, you will need to specify it explicitly in the Ansible playbook. Here Ansible become comes into the picture.
To execute the playbook as another user, you will need to provide the sudo feature. The Ansible become directive allows you to run commands as the specified user.
Ansible ‘become’ is used for privilege escalation. Ansible “become true” is used to activate privilege escalation. Ansible “become user” defines the user which is being used to execute the tasks which has the privileges to run that task.
Let’s try to understand this with the help of an example. Consider the below playbook:
-
name: this is our first play.
hosts: webserver
tasks:
-
name: "create a dummy file on websever1"
lineinfile: dest=/etc/resolv.conf line="gaurav0"
This playbook will write a line “gaurav0” to the file /etc/resolv.conf. Before that we need to check the user of this file, the user and group of the file is root.
And the user will be , “ansible_user=gaurrav”
In this case, the user ‘gaurrav’ should not be able to modify the file as it will be a security threat. Let’s try to run the playbook: