If you are not familiar with "become", check out Ansible - Understanding Become Privilege Escalation.
Let's say John Doe has been granted access to issue the reboot command using sudo. Let's say john.doe attempts to reboot server1 using the shell module and sudo.
--- - hosts: all tasks: - name: "reboot using sudo" shell: "sudo reboot"
Assuming the following option is commented out in ansible.cfg or set to true . . .
# command_warnings = False
. . . and you are not using the warn parameter, like this . . .
- name: "reboot using sudo" shell: "sudo reboot" warn: "false"
Invoking the play should return the following warning.
[WARNING]: Consider using 'become', 'become_method', and 'become_user' rather than running sudo
As the warning suggests, "become" should be used. There are different ways to use "become":
Here is how to use the become parameters in a playbook. Notice in this example that "sudo" is still used. This is because this example is using the shell module.
- name: "use the shell module, become root, sudo reboot" shell: "sudo reboot" become: yes
When using some other module, such as the file module, you would then use the "become_method" parameter.
- name: "mkdir /tmp/example" file: path: "/tmp/example" state: "directory" become: yes become_method: sudo
Assuming ansible.cfg does not contain the following . . .
Let's say the playbook is invoked like this.
The following will be returned.
sudo: a password is required
There are a few ways to address this.
The only time that the "become_user" parameter must be used is when you want to become some other user. For example, let's say John Doe has been granted permission to the reboot command, and Jane Doe is invoking the playbook.
[jane.doe server1]# ansible-playbook playbook.yml
In this scenario, the "become_user" parameter can be used so that Jane Doe can become John Doe. Of course, this assumes that Jane Doe will also be able to pass in John Doe's password, as described above.
- name: "use the shell module, become root, sudo reboot" shell: "sudo reboot" become: yes become_user: john.doe
Be aware that if the remote_user parameter is being used, and the remote_user is not the user you want to become, then you will need to use the become_user parameter.
--- - hosts: all remote_user: jane.doe tasks: - file: path: "/etc/foo" state: directory become: yes become_user: john.doe