本文介绍了在 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}} "

结果

jinja2.exceptions.TemplateRuntimeError: 没有名为 'ipaddr' 的测试

有没有什么办法可以使用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