Ansible 循环匹配 array/dict_list

Ansible loops matching on array/dict_list

我有一个这样的数组

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

在模板中,我想在给定的域上进行匹配,然后遍历 url 的内容

例如

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

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

    {% endfor %}
    {% endif %}

我确信 FOR 循环会正常工作,因为它在代码中其他地方的类似上下文中工作。

我只是在努力获得域名的条件匹配。

如有任何帮助,我们将不胜感激

谢谢

您似乎想为 our_domains 列表的每个元素执行 template 任务。

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

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

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

{% endfor %}
{% endif %}

如果另一方面,您打算只生成一个文件,则应使用此模板(在前面的代码中添加了一个 for 循环):

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