You need to enable JavaScript to run this app. 如何配置Ansible YAML清单嵌套组 无需重复罗列主机即可实现目标分组
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Ansible YAML清单嵌套组 无需重复罗列主机即可实现目标分组

问题根因

Ansible 中所有组名全局唯一,你在不同集群下定义的controller、compute实际指向同一个全局组。将全局controller设为cluster_one的子组后,controller内的所有主机(包括cluster_two的controller)都会自动归属到cluster_one,就会出现你遇到的跨集群主机混入的问题。

可行方案1:带前缀的角色组(无需插件,纯静态清单)

不需要重复罗列主机,仅通过组的嵌套关系实现需求,结构如下:

all:
  children:
    # 各集群角色组,名称带集群前缀避免全局冲突
    cluster_one_controller:
      hosts:
        host1:
        host2:
        host3:
    cluster_one_compute:
      hosts:
        host4:
        host5:
        host6:
    cluster_two_controller:
      hosts:
        host11:
        host12:
        host13:
    
    # 集群组:仅关联当前集群的角色子组
    cluster_one:
      children:
        cluster_one_controller:
        cluster_one_compute:
    cluster_two:
      children:
        cluster_two_controller:
    
    # 全局角色组:关联所有集群的对应角色子组
    controller:
      children:
        cluster_one_controller:
        cluster_two_controller:
    compute:
      children:
        cluster_one_compute:

该结构的效果完全匹配你的预期:

  • 执行ansible -i example.yml --list-hosts cluster_one仅返回host1~host6
  • 执行ansible -i example.yml --list-hosts controller返回所有集群的controller节点
  • 既可以用cluster_one:&controller筛选单集群controller,也可以直接用cluster_one_controller组实现相同效果

可行方案2:动态构造组(集群数量多的时候更易维护)

通过Ansible官方的constructed inventory插件,基于主机变量动态生成分组,完全没有重复配置:

  1. 首先编写基础静态清单,仅定义主机和对应属性:
# base.yml
all:
  hosts:
    host1: {cluster: "cluster_one", role: "controller"}
    host2: {cluster: "cluster_one", role: "controller"}
    host3: {cluster: "cluster_one", role: "controller"}
    host4: {cluster: "cluster_one", role: "compute"}
    host5: {cluster: "cluster_one", role: "compute"}
    host6: {cluster: "cluster_one", role: "compute"}
    host11: {cluster: "cluster_two", role: "controller"}
    host12: {cluster: "cluster_two", role: "controller"}
    host13: {cluster: "cluster_two", role: "controller"}
  1. 同目录下添加构造组配置constructed.yml:
plugin: constructed
strict: false
groups:
  # 按集群属性动态生成集群组
  cluster_one: cluster == "cluster_one"
  cluster_two: cluster == "cluster_two"
  # 按角色属性动态生成全局角色组
  controller: role == "controller"
  compute: role == "compute"
  1. 调整ansible.cfg启用constructed插件(如果没启用的话):
[inventory]
enable_plugins = host_list, script, auto, yaml, ini, constructed

后续新增主机仅需要添加对应cluster和role属性即可自动归入对应分组,新增集群或角色仅需要修改constructed.yml的分组规则,完全没有配置同步问题。

内容的提问来源于stack exchange,提问作者larsks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 14:24:01