过滤地址匹配条件
Filtering addresses matching condition
我想向我的服务器提供允许的 VLAN 列表作为变量。
Ansible 剧本应该能够根据此 VLAN 过滤服务器的 IP 地址。
我有一个服务器上所有可用 IP 地址的列表(ansible_all_ipv4_addresses
来自 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"
的模板
我在想:
1。神社之路
类似 从 my_subnets
项中提取 匹配 allowed_vlans
和 map 他们用 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
我想向我的服务器提供允许的 VLAN 列表作为变量。
Ansible 剧本应该能够根据此 VLAN 过滤服务器的 IP 地址。
我有一个服务器上所有可用 IP 地址的列表(
ansible_all_ipv4_addresses
来自 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"
我在想:
1。神社之路
类似 从 my_subnets
项中提取 匹配 allowed_vlans
和 map 他们用 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