Pedro Kuramoto
Pedro Kuramoto

Reputation: 31

ansible jinja2: nested dictionary

I'm trying to generate the following list:

list1:127.0.0.1,127.0.0.2
list2:192.168.1.1,192.168.1.254

From this dictionary:

ip_allowed:
    list1:
       - 127.0.0.1
       - 127.0.0.2
    list2:
       - 192.168.1.1
       - 192.168.1.254

Using the following jinja2 Ansible template:

#ZONE       HOST(S)               OPTIONS
{% for hosts_key, hosts_value in ip_allowed.iteritems() %}
   {% set hosts_dict = hosts_value %}
   {% for item in hosts_dict %}
      {{ hosts_key }}    {{ item }}
      {%- if loop.first %},{% endif %}
   {% endfor %}
{% endfor %}

But I'm getting the following result:

#ZONE       HOST(S)               OPTIONS
list1    127.0.0.1,         list1    127.0.0.2               list2    192.168.1.1,         list2    192.168.1.254

Upvotes: 0

Views: 233

Answers (1)

Zeitounator
Zeitounator

Reputation: 44809

I'm not entirely sure I got the exact format you want out of the template but you'll adapt if needed once you get the idea. Just join each ip in the value.

#ZONE       HOST(S)               OPTIONS
{% for allowed_item in (ip_allowed | dict2items) %}
{{ allowed_item.key }}    {{ allowed_item.value | join(',') }}
{% endfor %}

Upvotes: 1

Related Questions