Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 753
ScoSol Avatar asked Nov 19 '16 17:11

ScoSol


People also ask

What is Jinja2 template in Ansible?

Jinja2 templates are simple template files that store variables that can change from time to time. When Playbooks are executed, these variables get replaced by actual values defined in Ansible Playbooks. This way, templating offers an efficient and flexible solution to create or alter configuration file with ease.

What does pipe mean in Ansible?

With the pipe character you pass a value to a filter. There are numerous Jinja 2 filters but Ansible brings some additional filters. The term filter might be confusing at times because all the filters work very differently.


1 Answers

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.

like image 149
Konstantin Suvorov Avatar answered Oct 17 '22 06:10

Konstantin Suvorov