首页 > 解决方案 > ansible jinja2:嵌套字典

问题描述

我正在尝试生成以下列表:

list1:127.0.0.1,127.0.0.2
list2:192.168.1.1,192.168.1.254

从这本词典:

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

使用以下 jinja2 Ansible 模板:

#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 %}

但我得到以下结果:

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

标签: ansiblejinja2

解决方案


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 %}

推荐阅读