【问题标题】:ansible Jinja2 JSON loop last elementsansible Jinja2 JSON循环最后一个元素
【发布时间】:2018-05-29 18:38:21
【问题描述】:

我正在尝试使用从 Ansible 传递的变量从 Jinja2 模板生成 JSON 文件。据我所知,这里没有可以帮助我的模块(有待更正吗?)。

我卡在最后一个循环中

{
  "items": [
    {% for host in hostvars %}
    {"apiversion": "v1",
    "lastrunupdate": "{{ hostvars[host]['date'] }}",
    "hostname": "null",
    "hostip": "{{ hostvars[host]['inventory_hostname'] }}",
    "whoami": "{{ hostvars[host]['whoamiraw'] }}",
    "serialnumber": "{{ hostvars[host]['serial'] }}",
    "version": "{{ hostvars[host]['version'] }}",
    "ipaddress": "{{hostvars[host]['ipaddressraw'] }}",
    "users": [
        {% for hosts in hostvars[host]['listofusersraw'] %}

         {"user":"{{ listofusersraw[loop.index0].split(':')[0] }}" } {% if not loop.last %},{%else%}]},{% endif %}{% endfor %} 



      {% endfor %}
}
]
}

问题是最后一个循环将},添加到json列表的末尾。

【问题讨论】:

  • "请思考" ー 这里有一个想法:您应该首先通过从您发布的内容中删除不必要的代码来生成an MCVE"hostname": "null", 与问题相关吗?) ,然后通过添加缺失的位(因此其他人不必重新创建您省略的内容),最后通过明确指定您的期望是什么以及实际结果是什么。・例如你的“the last loop ads the }”在没有上下文的情况下是没有意义的:这是你想要的吗?这是您想要阻止的(以及如何阻止的?),但没有奏效?还是什么?

标签: ansible jinja2


【解决方案1】:

你的 jinja2 中有一些额外的字符。加逗号时去掉else:

{

    "items": [
                {% for host in hostvars %}
                    {"apiversion": "v1",
                    "lastrunupdate": "{{ hostvars[host]['date'] }}",
                    "hostname": "null",
                    "hostip": "{{ hostvars[host]['inventory_hostname'] }}",
                    "whoami": "{{ hostvars[host]['whoamiraw'] }}",
                    "serialnumber": "{{ hostvars[host]['serial'] }}",
                    "version": "{{ hostvars[host]['version'] }}",
                    "ipaddress": "{{hostvars[host]['ipaddressraw'] }}",
                    "users": [

                        {% for hosts in hostvars[host]['listofusersraw'] %}

                            {"user": "{{ listofusersraw[loop.index0].split(':')[0] }}" }

                            {% if not loop.last %}
                              ,
                            {% endif %}

                        {% endfor %}
                            ]
                {% endfor %}
                    }
            ]
}

注意:为了更易读,我已将其拆分。

【讨论】:

  • 谢谢,很抱歉最初的糟糕帖子,是漫长的一天!
猜你喜欢
  • 1970-01-01
  • 2016-02-22
  • 2020-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多