Question:
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.
Answer:
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
1 2 3 4 5 6 7 |
# inventory [group_A] 192.168.1.20 [group_B] 192.168.1.30 |
Then use conditionals on your tasks
1 2 3 4 5 6 7 8 |
- 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:
1 2 3 4 5 |
-tasks |- main.yml |- A_tasks.yml |- B_tasks.yml |
main.yml:
1 2 3 4 5 |
- include: A_tasks.yml when: "'group_A' in {{group_names}}" - include: B_tasks.yml when: "'group_B' in {{group_names}}" |
A_tasks.yml:
1 2 3 |
- name: run on A debug: msg="this only runs on A" |
B_tasks.yml:
1 2 3 |
- name: run on B debug: msg="this only runs on B" |