Define `become=yes' per role with Ansible
Solution 1:
I have found a solution, although I think a better solution should be implemented by the Ansible team. Rename main.yml to tasks.yml, and then write the following to main.yml:
---
- { include: tasks.yml, become: yes }
Another solution is to pass the parameter directly in site.yml, but the main idea of the question was reusing the role in other projects without forgetting it needs root:
---
- hosts: localhost
roles:
- { role: name, become: yes }
Solution 2:
You can also wrap your tasks in a block and put become: yes
on the block. So, inside your roles/role_name/tasks/main.yml
, you'd do this:
- block:
- name: Tasks go here as normal
...
become: yes
This will run all the tasks inside the block as root. More details of Ansible's blocks here (latest docs).
Solution 3:
Not really a fundamentally different answer, rather a cosmetic reformatting of what's already been said. Looks the shortest, cleanest and YAML-ishest to me:
- name: My play
hosts: myhosts
roles:
- role: role1
become: yes
- role: role2
Role1 will be run as root while role2 won't.