How can I run an imported Ansible playbook for each unique value in a set of host vars?

I’ve got a playbook which needs to run against my entire inventory, with a list of hostnames as an extra variable (target_hosts).

The hosts in target_hosts all have a group_id hostvar defined on them. I use the whole inventory because some ancillary hosts which correspond to the group_id var need per-group configuration to match in one section.

There will often be multiple group_id values associated with the hosts in the target_hosts list. I need to select the correct inventory group of ancillary hosts and import/run a playbook to configure both sets of servers partway through the main playbook.

This is what I currently do:

include_playbook: group-configure.yaml
vars:
src_hosts: “group-{{ group_id }}-ancillary-1”
dest_hosts: “{{ target_hosts }}”

I currently have to manually separate the target_hosts by group_id manually, then run the main playbook once for each. This has tons of unnecessary overhead.

What I really want to execute is this:

for each group of hosts from target_hosts with the same group_id hostvar:
import and run group-configure.yaml with:
src_hosts: “ancillary-{{ group_id }}”
target_hosts: restricted to those with that value of group_id

How can I do this? If the current way this is structured won’t work, what’s the best alternative approach?

Thanks for any help!

Ewan

The easiest way to target a group of host is to sepcify it when you trigger call your ansible-playbook command, to have it working properly you need to target all hosts in the playbook itself,

group-configure.yaml

  • name: group-configure
    hosts: all

tasks:

/group-configure.yaml

Then run the playbook on the group of your inventory

ansible-playbook -l target_hosts group-configure.yaml

hope that help.

Matth