问题
Im trying to produce a JSON file from a Jinja2 template using variables passed from Ansible. As far as I know there are no modules that help me here (stand to be corrected?).
Im stuck on the last loop
{
"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 %}
}
]
}
The issue is that the last loop adds },
to the end of the json list.
回答1:
You have some extra characters in your jinja2. Remove the else when adding the comma:
{
"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 %}
}
]
}
Note: I have splitted it to be more readable.
来源:https://stackoverflow.com/questions/50590896/ansible-jinja2-json-loop-last-elements