ansible Jinja2 JSON 循环最后一个元素

标签 ansible jinja2

我尝试使用从 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 列表的末尾。

最佳答案

你的 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 %}
                    }
            ]
}

Note: I have splitted it to be more readable.

关于ansible Jinja2 JSON 循环最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50590896/

相关文章:

python - 防止 ansible 使用 sudo

python - Ansible + Ubuntu 18.04 + MySQL = "The PyMySQL (Python 2.7 and Python 3.X) or MySQL-python (Python 2.X) module is required."

python - Flask 路由顺序很重要吗?

python - 在 Jinja2 中使用 babel 链接

ansible - 在 Ansible 的 Jinja2 模板中获取列表的第一个 "N"元素

docker - Ansible:遍历库存组

python - 使用 Ansible 解析带有命名空间的 XML,特别是 JBOSS standalone.xml

当我使用变量时,ansible playbook语法错误

javascript - 在 Flask 中将客户端数据传输到服务器端

python - 如何循环遍历所有列表项并从每个键中提取值?