Ansible循环匹配array / dict_list

时间:2018-05-14 14:08:09

标签: ansible ansible-2.x ansible-template

我有一个像这样的数组

our_domains:
  - domain: www.example.com
    urls:
      - { path: '/' }
      - { path: '/test1' }
  - domain: www.example2.com
    urls:
      - { path: '/' }
      - { path: '/test2' }

在模板中我想在给定的域上匹配,然后循环遍历urls的内容

e.g

    {% if item.value.domain == 'www.example2.com' %}
    {% for item_url in item.urls %}

   service_description    http://anotherwebsite.com{{ item_url['path'] }}

    {% endfor %}
    {% endif %}

我确信FOR循环可以正常工作,因为它在代码中的其他地方工作。

我正在努力在域名上获得条件匹配。

任何帮助将不胜感激

由于

1 个答案:

答案 0 :(得分:1)

看起来您想要为template列表的每个元素执行our_domains任务。

你应该从value语句中删除if,其余的看起来很好:

{% if item.domain == 'www.example2.com' %}
{% for item_url in item.urls %}

service_description    http://anotherwebsite.com{{ item_url['path'] }}

{% endfor %}
{% endif %}

如果另一方面,你的意图是只生成一个文件,你应该使用这个模板(还有一个用于循环添加封闭前面的代码):

{% for item in our_domains %}
{% if item.domain == 'www.example2.com' %}
{% for item_url in item.urls %}

service_description    http://anotherwebsite.com{{ item_url['path'] }}

{% endfor %}
{% endif %}
{% endfor %}