在Ansible Jinja模板中的嵌套循环

时间:2016-07-08 00:33:39

标签: loops yaml ansible jinja2

我正在使用ansible来构建一些swatch conf文件,试图让它尽可能灵活,以允许不同的操作。我被困在.j2文件中的嵌套循环中。我有这样的Ansible vars:

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%}错误。它最终只写第二个动作和阈值。我认为它会覆盖第一个?

1 个答案:

答案 0 :(得分:1)

看起来像纯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"