Ansible:有没有办法从列表中检查 IP 地址和 return 子网(如果存在)?

Ansible: Is there a way to check for an IP address and return a subnet from a list, if present?

我的任务是使用 Ansible 设置检查以验证 IP 地址是否包含在子网中。

我已经设置了一个测试剧本,我在其中完成了以下操作:

tasks:
   - name: "Include_vars"
      include_vars:
         file: /vlans.yml
   - name: "Set_fact"
      set_fact:
         test_item "{{ item | string | split (':') | last }}"
      loop: "{{ vlans }}"

在 vlans.yml 中,文件包含 VLAN 子网列表,格式如下:

vlans:
   - "vlan-1-external:10.0.1.0/24"
   - "vlan-2-internal:10.0.2.0/24"
   [...]

剧本管理 - 使用 debug 指令 - 拆分给定的字符串,并且仅 return 子网,如 10.0.1.0/24

我的 objective 是让剧本评估列表中的每个 VLAN,将 IP 作为参数传递,然后 returning 包含该 IP 地址的特定 VLAN。

我查看了 ipaddr 过滤器,但我看不到任何执行此类检查的方法。

有人知道执行我正在寻找的检查的方法吗?

提前感谢您的任何提示。

问:“验证 IP 地址是否包含在子网中。”

A:Test循环中的IP地址列表,例如

    - debug:
        msg: "{{ item.0 }}: {{ test_list|ansible.netcommon.ipaddr(item.1) }}"
      loop: "{{ vlans|map('split', ':')|list }}"
      vars:
        test_list:
          - 10.0.1.99
          - 10.0.2.99
          - 10.0.3.99

给出(删节)

  msg: 'vlan-1-external: [''10.0.1.99'']'
  msg: 'vlan-2-internal: [''10.0.2.99'']'

可选,首先将列表转换为字典

vlans_subnet: "{{ dict(vlans|map('split', ':')) }}"

给予

  vlans_subnet:
    vlan-1-external: 10.0.1.0/24
    vlan-2-internal: 10.0.2.0/24

然后,测试循环中的IP地址列表

    - debug:
        msg: "{{ item.key }}: {{ test_list|ansible.netcommon.ipaddr(item.value) }}"
      loop: "{{ vlans_subnet|dict2items }}"
      vars:
        test_list:
          - 10.0.1.99
          - 10.0.2.99
          - 10.0.3.99

给出(删节)

  msg: 'vlan-1-external: [''10.0.1.99'']'
  msg: 'vlan-2-internal: [''10.0.2.99'']'

除了弗拉基米尔的回答,还有另一种方法可以做到这一点:

首先,设置映射列表如

vlans:
  - name: "vlan-1-internal"
    network: "192.168.1.0/24"
    [...]

然后循环遍历此列表并使用network_in_usable,以验证IP 地址是否在该列表中。然后,将其转换为 JSON 对象:

vlan:
  {% set map = [] %}
    {% for object in vlans %}
      {%if (object.network | ansible.netcommon.network_in_usable(ip_to_check) ) %}
      {% set x=map.append({
        "name": object.name
        "network": object.network
        [...]
       }) %}
     {% endif %}
   {% endfor %}
  {{ map | to_json }}

希望对您有所帮助。