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

I am writing an Ansible template that needs to create an ip list in a host group, excluding the current host IP. I searched on the Internet and through the documentation, but did not find any filters to remove the item from the list. I created (hacky) for the loop below to do this, but wondered if anyone knew of the โ€œbest practiceโ€ of such filtering.

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

Suppose that the groups ['my_group'] have 3 ip (192.168.1.1, 192.168.1.2 and 192.168.1.3). When a template is created for 192.168.1.1, it should print only ip 192.168.1.2 and 192.168.1.3.

+5
source share
1 answer

Here's the difference filter :

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

This will give you all the element nodes from my_group without the current host.

+10
source

Source: https://habr.com/ru/post/1260012/


All Articles