filter a list of objects with ipaddr in Ansible

2019-08-09 08:01发布

问题:

If I had a list of ip addresses in Ansible, I could use the ipaddr filter to it and only get the passing values back:

- debug:
    msg: "{{ ['127.0.0.1', 'foo', '2001:db8:32c:faad::'] | ipaddr('address') }}"

Unfortunately I am working with a list of objects (hostvars of group members to be precise). I want to do some tests on the list and only keeping the entries passing - but as objects.

When reading the Jinja docs I stumbled across selectattr. Unfortunately it seems that ipaddr isn't a test, so it doesn't work:

- debug:
    msg: "{{ [{'ip':'127.0.0.1'}, {'ip':'foo'}, {'ip':'2001:db8:32c:faad::'}] | selectattr('ip', 'ipaddr', 'address') | list}} "

results in

jinja2.exceptions.TemplateRuntimeError: no test named 'ipaddr'

Is there any way to use ipaddr to filter a list of objects?

回答1:

Is there any way to use ipaddr to filter a list of objects?

Sure! You can use the map function to apply the filter to your list to get a list of (effectively) true/false values, and then use that in combination with your original list to select only entries with a valid address. For example:

---
- hosts: localhost
  gather_facts: false
  vars:
    addresses:
      - name: host0
        ip: 127.0.0.1
      - name: host1
        ip: foo
      - name: host2
        ip: '2001:db8:32c:faad::'
  tasks:
    - set_fact:
        valid_addresses: "{{ addresses|json_query('[*].ip')|map('ipaddr')|list }}"

    - debug:
        msg: "host {{ item.0.name }} has valid address {{ item.0.ip }}"
      when: item.1
      loop: "{{ addresses|zip(valid_addresses)|list }}"