There is a way to do what you are asking, but you need to be careful with how you use it, because Ansible evaluates most vars before running any tasks. If you use this trick, you must be sure to use it consistently or you could unintentionally use become
where you don't want to.
Under the hood, Ansible uses the variable ansible_become
to determine whether to use become for that task. Within your role, you can create a defaults/main.yml
and set ansible_become: [true/false]
This will cause that entire role to accept that value, unless overwritten by a higher-precedence definition (important to understand variable precedence)
The critical "gotcha" here is that if you use a role where this is defined, it will affect all other roles called below it in the play, unless they also have it defined.
Examples:
role_default_become_true
has ansible_become: true
defined as true in defaults
role_default_become_false
has ansible_become: false
defined as true in defaults
role_no_default
has no default ansible_become
value
---
- name: test1
hosts: localhost
connection: local
roles:
- role_default_become_true
- role_default_become_false
- role_no_default
- name: test2
hosts: localhost
connection: local
roles:
- role_default_become_false
- role_default_become_true
- role_no_default
- name: test3
hosts: localhost
connection: local
roles:
- role_default_become_false
- role_default_become_true
- { role: role_no_default, become: false }
In test1, role_no_default
will run without become, because the previous role defined it as false, and it does not have its own definition.
In test2, role_no_default
will run with become, because the previous role defined it as true, and it does not have its own definition.
In test3, role_no_default
will run without become, because it has its own definition.
include_role
requiresapply: become: yes
docs.ansible.com/ansible/latest/modules/…