本文介绍了在Ansible中使用ipaddr过滤对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在Ansible中有一个IP地址列表,则可以对它使用ipaddr过滤器,并且只获取传回的值:

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

不幸的是,我正在使用对象列表(精确地说是组成员的 hostvars ).我想对列表进行一些测试,并且仅使条目通过-而是作为对象.

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.

在阅读Jinja文档时,我偶然发现了selectattr.不幸的是,ipaddr似乎不是测试,所以它不起作用:

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

产生

是否可以使用ipaddr过滤对象列表?

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

推荐答案

当然!您可以使用map函数将过滤器应用于列表以获取(有效)true/false值的列表,然后将其与原始列表结合使用以仅选择具有有效地址的条目.例如:

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

这篇关于在Ansible中使用ipaddr过滤对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 23:34