2016-07-08 210 views
1

我正在使用ansible構建一些swatch conf文件,試圖使其儘可能靈活以允許進行不同的操作。我被困在.j2文件中的嵌套循環中。我有這樣的Ansible瓦爾這樣:在Ansible Jinja模板中嵌套循環

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 

它通過循環{item.watchfor循環%}循環{%for watchfor循環罰款,但然後我有{%for actionfor watchfor.actions%}以某種方式錯誤。它最終只寫第二個動作和閾值。我認爲它會覆蓋第一個?

回答

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" 
+0

謝謝,@udondan,那確實是我的問題。 – Blake