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":
- Use the become command line flags - this will take precendence over all other approaches (that's what we will describe in this article)
- Use the become parameters in a playbook
- Use the become connection variables (uncommon)
- Use the become directives in ansible.cfg (very uncommon)
Here is how to use the "--become" command line flag.
ansible-playbook playbook.yml --become
When using some other module, such as the file module . . .
- name: "mkdir /tmp/example"
file:
path: "/tmp/example"
state: "directory"
you would then also use the "--become_method" command line flag.
ansible-playbook playbook.yml --become --become-method=sudo
Assuming ansible.cfg does not contain the following . . .
become_pass: your_password
Let's say the playbook is invoked like this.
ansible-playbook playbook.yml
The following will be returned.
sudo: a password is required
There are a few ways to address this.
- Use the --ask-become-pass command line flag
- Use the --vault-password-file command line flag
- Define become_pass in ansible.cfg
The --ask-become-pass flag should produce a prompt asking for your password.
BECOME password:
become_user
The only time that the "--become_user" command line flag 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. 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.
[jane.doe server1]# ansible-playbook playbook.yml --become --become-user=john.doe
remote_user
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 command line flag.
---
- hosts: all
remote_user: jane.doe
tasks:
- file:
path: "/etc/foo"
state: directory
Did you find this article helpful?
If so, consider buying me a coffee over at