过滤地址匹配条件

Filtering addresses matching condition

我想向我的服务器提供允许的 VLAN 列表作为变量。

Ansible 剧本应该能够根据此 VLAN 过滤服务器的 IP 地址。

我正在寻找一种方法来制作 "192.168.2.0/24""192.168.5.0/24"

的模板

我在想:

1。神社之路

类似 my_subnets 项中提取 匹配 allowed_vlansmap 他们用 ansible_all_ipv4_addresses 通过 ipaddr() 过滤器。

2。 JSON查询方式

我试过:

{{ my_subnets | json_query('[?vlan in allowed_vlans].subnet') }}

但似乎 json_query 没有使用 python 语法来评估数组中是否有内容。

contains() function is how JMESPath checks for membership, but as best I can tell it has no ability to refer upward in the object tree, nor assign expressions to internal variables as does the jq language. But, one can cheat and serialize the expression to JSON and then use JMESPath's literal expression语法:

tasks:
- debug:
    verbosity: 0
    msg: |
      {{ my_subnets | json_query(jq) }}
  vars:
    # this "vars" trick was recommended by the json_query docs, but isn't required
    jq: |
      [? contains(`{{ allowed_subnets | to_json }}`, vlan) ].subnet