ansible template with if condition inventory name

Viewed 251

Actually I try to create network configs for a network bridge. For this I have the following in group_vars.

---
backbone_ip:
- name: server2
  ipv4: 111.111.111.2/24
  ipv6: 2001:111:111:1::2/64
- name: server3
  ipv4: 111.111.111.3/24
  ipv6: 2001:111:111:1::3/64
- name: server5
  ipv4: 111.111.111.5/24
  ipv6: 2001:111:111:1::5/64

With the template Module I write the config. The template:

auto br-{{ bridge_network }}
iface br-{{ bridge_network }} inet static
{% for server in backbone_ip %}
{% if server.name in hostvars[host].inventory_hostname %}
        address {{ server.ipv4 }}
        bridge_ports none
        bridge_stp off
        bridge_fd 0

iface br-{{ bridge_network }} inet6 static
        address {{ server.ipv6 }}
{% endif %}
{% endfor %}

Now my problem is that i want only write the lines if server.name is the inventory name of the server ansible actually connected to.

hostvars[host].inventory_hostname seems to be wrong. shouĺd a change in to = or how is the syntax?

Thanks pr0

1 Answers

The list is a wrong structure for this use-case. Change it to a dictionary, e.g.

  backbone_dict:
    server2:
      ipv4: 111.111.111.2/24
      ipv6: 2001:111:111:1::2/64
    server3:
      ipv4: 111.111.111.3/24
      ipv6: 2001:111:111:1::3/64
    server5:
      ipv4: 111.111.111.5/24
      ipv6: 2001:111:111:1::5/64

Then addressing of the attributes is trivial, e.g.

    - debug:
        msg: "{{ backbone_dict[inventory_hostname].ipv4 }}"

If you can't change the structure of the data convert it first, e.g.

    - set_fact:
        backbone_dict: "{{ dict(_keys|zip(backbone_ip)) }}"
      vars:
        _keys: "{{ backbone_ip|map(attribute='name')|list }}"
      run_once: true
Related