过滤地址匹配条件 [英] Filtering addresses matching condition

查看:26
本文介绍了过滤地址匹配条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将允许的 VLAN 列表作为变量提供给我的服务器.

I want to provide list of allowed VLAN's as a variable to my server.

Ansible playbook 应该能够根据这个 VLAN 过滤服务器的 IP 地址.

Ansible playbook should be able to filter server's IP addreses based on this VLAN's.

  • 我有服务器上所有可用 IP 地址的列表(ansible_all_ipv4_addresses 来自 ansible 事实)

  • I have a list of all IP addresses available on server (ansible_all_ipv4_addresses from ansible facts)

我有一个全局变量 my_subnets:

my_subnets:
  - vlan: 2
    subnet: "192.168.2.0/24"
    gateway: "192.168.2.10"
  - vlan: 3
    subnet: "192.168.3.0/24"
    dns: "192.168.3.12"
  - vlan: 4
    subnet: "192.168.4.0/24"
  - vlan: 5
    subnet: "192.168.5.0/24"

  • 我有每个服务的变量 allowed_vlans:

    allowed_vlans:
      - 2
      - 5
    

  • 我正在寻找一种方法来模板化 "192.168.2.0/24""192.168.5.0/24"

    I am looking for a way how to template out just "192.168.2.0/24" and "192.168.5.0/24"

    我在想:

    类似从 my_subnetsmatching allowed_vlansextractmap 之类的东西ansible_all_ipv4_addresses 通过 ipaddr() 过滤器.

    Something like extract from my_subnets items matching allowed_vlans and map them with ansible_all_ipv4_addresses through ipaddr() filter.

    我试过了:

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

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

    but it seems the json_query is not using python syntax for evaluating if something is in array.

    推荐答案

    contains() 函数是 JMESPath 检查成员资格的方式,但据我所知,它无法在对象树中向上引用,也不能像jq 语言.但是,可以欺骗并将表达式序列化为 JSON,然后使用 JMESPath 的 literal expression 语法:

    The 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 syntax:

    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
    

    这篇关于过滤地址匹配条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆