How to remove or exclude an item in an Ansible template list?

泄露秘密 提交于 2019-12-04 18:19:22

问题


I'm writing an Ansible template that needs to produce a list of ip's in a host group, excluding the current hosts IP. I've searched around online and through the documentation but I could not find any filters that allow you to remove an item in a list. I have created the (hacky) for loop below to do this but was wondering if anyone knew a "best practice" way of filtering like this.

{% set filtered_list = [] %}

{% for host in groups['my_group'] if host != ansible_host %}
    {{ filtered_list.append(host)}}
{% endfor %}

Lets say groups['my_group'] has 3 ip's (192.168.1.1, 192.168.1.2 and 192.168.1.3). When the template is generated for 192.168.1.1 it should only print the ip's 192.168.1.2 and 192.168.1.3.


回答1:


There is difference filter for that:

- debug: var=item
  with_items: "{{ groups['my_group'] | difference([inventory_hostname]) }}"

This will give you all items hosts from my_group without current host.



来源:https://stackoverflow.com/questions/40696130/how-to-remove-or-exclude-an-item-in-an-ansible-template-list

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