Ansible Jinja 模板中的嵌套循环

Nested Loop In An Ansible Jinja Template

我正在使用 ansible 构建一些样本 conf 文件,试图使其尽可能灵活以允许不同的操作。我卡在 .j2 文件中的嵌套循环中。我有这样的 Ansible 变量:

swatch_files:
  - name: 'syslog'
    tail: '/var/log/syslog'
    watchfor:
      -
        string: 'Stupid FIrst String'
        actions:
          -
            action: "1/2 Slack blah blah action"
            threshold: "Threshold For This first Action"
        actions:
          -
            action: "2/2 Slack blah blah action"
            threshold: "Threshold For This second Action"
      -
        string: 'Crappy Second String'
        actions:
          -
            action: "1/2 Slack blah blah action"
            threshold: "Threshold For This 1 Action"
        actions:
          -
            action: "2/2 Slack blah blah action"
            threshold: "Threshold For This 2 Action"

任务确实创建了文件:

- name: Swatch | Create the Monit swatch conf files   template:
    src="swatch.monit.j2"
    dest="/etc/monit/conf.d/{{ item.name }}.conf"
    owner=root
    group=root
    mode=0700   with_items: swatch_files   tags:
    - monit

我的 swatch.conf.j2 文件如下所示:

{% for watchfor in item.watchfor recursive %}
   watchfor /{{ watchfor.string }}/
{% for actions in watchfor.actions %}
        Action: {{ actions.action }}
        Threshold: {{ actions.threshold }}
{% endfor %}
{% endfor %

但是我的 /etc/swatch/syslog.conf 最终是这样的:

   watchfor /Stupid FIrst String/
    Action: 2/2 Slack blah blah action
    Threshold: Threshold For This second Action

   watchfor /Crappy Second String/
    Action: 2/2 Slack blah blah action
    Threshold: Threshold For This 2 Action

它通过 {% for watchfor in item.watchfor recursive %} 循环正常,但后来我的 {% for actions in watchfor.actions %} 不知何故出错了。它最终只写了第二个动作和阈值。我假设它会覆盖第一个?

看起来像是一个纯 YAML 问题。您正在覆盖字典中的键 actions

watchfor:
  -
    string: 'Stupid FIrst String'
    actions:
      -
        action: "1/2 Slack blah blah action"
        threshold: "Threshold For This first Action"
    actions:
      -
        action: "2/2 Slack blah blah action"
        threshold: "Threshold For This second Action"

如果您的 actions 列表应该有多个项目,它应该如下所示:

watchfor:
  - string: 'Stupid FIrst String'
    actions:
      - action: "1/2 Slack blah blah action"
        threshold: "Threshold For This first Action"
      - action: "2/2 Slack blah blah action"
        threshold: "Threshold For This second Action"