Ansible 2字典交集

时间:2016-12-01 18:32:14

标签: ansible

on Ansible 2.2我有

all_subnets:
id   | subnet         | mask | sectionId 
-----+----------------+------+-----------
4831 | 172.31.0.0     | 16   | 19        
4832 | 192.168.0.0    | 24   | 19        
4858 | 192.168.248.0  | 21   | 19        
4859 | 192.168.248.0  | 27   | 19        
4860 | 192.168.248.32 | 28   | 19        

和另一个包含预期子网的json列表

my_subnets:
  - subnet: "192.168.0.0"
    mask: "24"
  - subnet: "192.168.248.32"
    mask: "28"

现在,我想与两个列表相交:

id   | subnet         | mask | sectionId 
-----+----------------+------+-----------
4832 | 192.168.0.0    | 24   | 19        
4860 | 192.168.248.32 | 28   | 19        

我怎样才能做到这一点?

的Riccardo

1 个答案:

答案 0 :(得分:0)

在这种情况下,我更喜欢重构顶级数据库"字典的值(可能是由ID键控)。此格式可以根据ID或其他属性轻松访问值的子集,或访问整组值。

这也与Ansible的口头禅保持简单相符,最大限度地减少交叉点和匹配等复杂问题的需要。

例如:

---
all_subnets:
  4831: { id: 4831, subnet: "172.31.0.0",     mask: 16, sectionId: 19, }
  4832: { id: 4832, subnet: "192.168.0.0",    mask: 24, sectionId: 19, }
  4858: { id: 4858, subnet: "192.168.248.0",  mask: 21, sectionId: 19, }
  4859: { id: 4859, subnet: "192.168.248.0",  mask: 27, sectionId: 19, }
  4860: { id: 4860, subnet: "192.168.248.32", mask: 28, sectionId: 19, }

# Your use-case
my_subnets: ["{{ all_subnets[4832] }}", "{{ all_subnets[4860] }}"]

# Getting subnets matching a value
my_subnets: "{{ all_subnets | selectattr('subnet', 'equalto', '192.168.248.0') | list }}"

# Getting all subnets
my_subnets: "{{ all_subnets.values() }}"