You need to enable JavaScript to run this app. Ansible嵌套字典循环:筛选非inventory_hostname的子网配置
优惠活动
大模型
产品
解决方案
定价
更多

Ansible嵌套字典循环:筛选非inventory_hostname的子网配置

实现方案

核心逻辑

通过Ansible内置字典处理过滤器,将原模板场景下的两层嵌套循环逻辑,直接转换为可用于任务循环的一维配置列表。循环过程中每次迭代拿到的对象会直接包含独立的subnet、subnet_mask、subnet_cidr字段,可直接作为防火墙配置类任务的入参使用,无需依赖模板渲染或自定义嵌套循环。

循环数据构造流程

按照过滤、拆解、扁平化的顺序组合内置过滤器:

  • 用dict2items将servers字典转换为包含key、value结构的键值对列表
  • 用selectattr筛选出所有key不等于当前执行节点inventory_hostname的条目,排除当前主机自身对应的网段配置
  • 提取筛选后条目的value(即对端主机下的所有网卡配置字典),再次通过dict2items将每个网卡配置拆分为独立条目
  • 用flatten将多层嵌套结构拍平为一维列表,最后提取每个条目的value,得到最终的子网配置对象列表

完整任务代码

tasks:
  - debug:
      msg: "{{ item['subnet'] }}/{{ item['subnet_cidr'] }}"
    loop: >
      {{ servers
      | dict2items
      | selectattr('key', 'ne', inventory_hostname)
      | map(attribute='value')
      | map('dict2items')
      | flatten
      | map(attribute='value')
      }}

执行效果

在alpha.lan节点运行时,输出结果完全匹配预期:

"msg": "172.16.0.0/22"
"msg": "172.16.4.0/22"

可读性优化

如果多个任务需要复用该子网列表,可将过滤器链的结果定义为独立变量,避免重复编写长串表达式:

vars:
  remote_server_subnets: >
    {{ servers
    | dict2items
    | selectattr('key', 'ne', inventory_hostname)
    | map(attribute='value')
    | map('dict2items')
    | flatten
    | map(attribute='value')
    }}

tasks:
  - debug:
      msg: "{{ item['subnet'] }}/{{ item['subnet_cidr'] }}"
    loop: "{{ remote_server_subnets }}"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.14 04:36:07