In Ansible, how to filter a dictionary based on regex pattern on the keys?

Viewed 4517

I need to extract a subset of a dictionary based on a pattern on the key names. For example, in the v below I need to extract the key->values section1*.

The code below assigns the list of values, but I still haven't found a way to preserve the key->map setting.

  - 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

Any help, please? Thanks.

2 Answers

Combine dict2items and items2dict filters:

- 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 }}"}

If I look at the sources in /usr/lib/python2.7/dist-packages I see that there are references to it, but not real function definitions

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,

I'm runing 2.5.1. Do I need a later version?

Related