【问题标题】:Nested Loop In An Ansible Jinja TemplateAnsible Jinja 模板中的嵌套循环
【发布时间】:2016-07-08 00:33:38
【问题描述】:

我正在使用 ansible 构建一些 swatch 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 %} 不知何故错了。它最终只写了第二个动作和阈值。我假设它会覆盖第一个?

【问题讨论】:

    标签: loops yaml ansible jinja2


    【解决方案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"
    

    【讨论】:

    • 谢谢@udondan,这确实是我的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多