I have a created a role, where I have defined all ansible tasks. Also I have host A and host B in the inventory. Is it possible to execute 90% of task on host A and 10% of task on host B? My Ansible controller is host C.
The first way I can think to do this is with conditionals based on inventory.
Create a group in inventory for A, and a group for B. I will call these group_A and group_B
# inventory
[group_A]
192.168.1.20
[group_B]
192.168.1.30
Then use conditionals on your tasks
- name: run this on A
debug: msg="this runs only on A
when: "'group_A' in {{group_names}}"
- name: run this on B
debug: msg="this runs only on B
when: "'group_B' in {{group_names}}"
Depending on how many tasks you have, it may be too much to put a conditional on every task, so you can use conditionals on includes, like so:
file structure:
-tasks
|- main.yml
|- A_tasks.yml
|- B_tasks.yml
main.yml:
- include: A_tasks.yml
when: "'group_A' in {{group_names}}"
- include: B_tasks.yml
when: "'group_B' in {{group_names}}"
A_tasks.yml:
- name: run on A
debug: msg="this only runs on A"
B_tasks.yml:
- name: run on B
debug: msg="this only runs on B"
If you're splitting all of the tasks in one role between two different hosts, then neither of those hosts really has that role, do they? I'd say it's an abuse of the role system to congregate all of those tasks into one role when you really have two.
What happens if you have multiple host As? What about multiple host Bs?
It seems to me you don't actually want to use a role here - you want to use just a plain ol' playbook.
- hosts: A
tasks:
[...]
- hosts: B
tasks:
[...]
Playbooks are for defining a series of actions in a particular order, and your "do this stuff on B only after doing this stuff on A" is that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With