filter a list of objects with ipaddr in Ansible

夙愿已清 提交于 2019-12-24 08:59:27

问题


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


来源:https://stackoverflow.com/questions/56023464/filter-a-list-of-objects-with-ipaddr-in-ansible

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!