在Ansible中,如何根据键上的正则表达式模式过滤字典



我需要根据关键字名称的模式提取字典的子集。例如,在下面的v中,我需要提取key->values section1*。

下面的代码分配了值列表,但我仍然没有找到一种方法来保留key->map设置。

- set_fact:
v:
section1_1: true
section1_2: false
section2_1: true
section2_2: false
section3: true
- set_fact:
v2: "{{ v | select('match','^section1_.*') | map('extract', v) | list }}"
- debug:
var: v2

有什么需要帮忙的吗?谢谢

组合dict2itemsitems2dict过滤器:

- debug:
msg: "{{ v | dict2items | selectattr('key', 'match', '^section1') | list | items2dict }}"
fatal: [localhost]: FAILED! => {"msg": "template error while templating string: no filter named 'items2dict'. String: {{  v | dict2items | selectattr('key', 'match', '^section1_') | list | items2dict }}"}

如果我查看/usr/lib/python2.7/dist-packages中的源代码,我会发现有对它的引用,但没有真正的函数定义

ansible/plugins/filter/core.py:        raise AnsibleFilterError("items2dict requires a list, got %s instead." % type(mylist))
ansible/plugins/filter/core.py:            'items2dict': list_of_dict_key_value_elements_to_dict,

我的成绩是2.5.1。我需要更高版本吗?

最新更新