ansible Jinja2 JSON loop last elements

梦想与她 提交于 2021-02-16 20:09:26

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!