运行 一组主机变量中每个唯一值的导入 Ansible 剧本

Run an imported Ansible playbook for each unique value in a set of host vars

我有一个剧本需要 运行 对我的整个库存,主机名列表作为一个额外的变量 (target_hosts)。

target_hosts 中的主机都定义了 group_id hostvar。我使用整个清单,因为一些对应于 group_id var 的辅助主机需要每组配置在一个部分中匹配。

通常会有多个 group_id 值与 target_hosts 列表中的主机关联。我需要 select 正确的辅助主机清单组和 import/run 剧本来配置主剧本中途的两组服务器。

这是我目前所做的:

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

我目前必须手动将 target_hostsgroup_id 手动分开,然后 运行 每个主剧本一次。这会产生大量不必要的开销。

我真正要执行的是:

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`'

我该怎么做?如果当前的结构化方式行不通,最好的替代方法是什么?

我很确定 add_host: combined with groupby 就是您要找的东西,它将允许您按属性汇总这些主机,然后 运行 针对他们的剧本就好像那组一样已经定义:

- hosts: localhost
  connection: local
  gather_facts: no
  become: no
  vars:
    list_of_name_groups: >-
        {%- set results = [] -%}
        {%- for g_id, items in (dict(hostvars) | dict2items | groupby("value.group_id")) -%}
        {%- for hostname in (items | map(attribute="key") | list) -%}
        {%- set _ = results.append({"group_id": g_id, "hostname": hostname}) -%}
        {%- endfor -%}
        {%- endfor -%}
        {{ results }}
  tasks:
  - add_host:
      name: '{{ item.hostname }}'
      groups: ancillary-{{ item.group_id }}
    with_items: '{{ list_of_name_groups }}'

- hosts: ancillary-my-awesome-groupid
  # etc etc