I want to loop over a task in my playbook with different items (for example, put a bunch of templated files on the host machine). I also want to execute this specific task on a group of hosts (A) that is not the same as the list of hosts defined at the start of the play book (B). A is a subset of B.
I’ve read online that you can use a for loop over a host group and use the items for the delegate_to field. But then I can’t loop over other items, right?
- name: do stuff on loop on a couple of hosts
ansible.builtin.copy:
src: "files/{{ item }}"
dest: "/etc/blahfolder/{{ item }}"
loop: "{{ file_list }}"
delegate_to: "{{ other_items? }}"
another_loop?: "{{ couple_of_hosts }}"
Simplest way would be to duplicate your task in two plays, or writing your task elsewhere and call it in your separate plays using ansible.builtin.import_tasks: (or include for dynamic reuse), targeting specific hosts for each play.
Here is a simple example with two plays running a duplicated task on their specified hosts:
You could also use delegate_to: on your task, with run_once: true (since delegated tasks will indeed be executed on hosts you define in delegate_to:, but for each host you target on your play, so effectively running your task n times on delegated node, n being the number of hosts your play targets. Weird, I know).
Here is an example using delegate_to: (and run_once: true), looping through another hosts list: