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

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

问题描述

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

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

Ansible剧本应该能够基于此VLAN过滤服务器的IP地址.

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

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

我有一个全局变量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_subnets个项目匹配 allowed_vlans映射提取之类的东西,并通过 ipaddr()用ansible_all_ipv4_addresses映射它们过滤器.

    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() 向上,也无法像jq语言那样将表达式分配给内部变量.但是,您可以将表达式作弊并将其序列化为JSON,然后使用JMESPath的文字表达式语法:

    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天全站免登陆