【发布时间】: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 }”在没有上下文的情况下是没有意义的:这是你想要的吗?这是您想要阻止的(以及如何阻止的?),但没有奏效?还是什么?