Json 向Ansible变量递归添加字典

Json 向Ansible变量递归添加字典,json,ansible,jinja2,Json,Ansible,Jinja2,我在Ansible playbook中有一个变量,我需要填充来自主机的信息。如果我以静态方式填充它: mongodb_replication_params: - { host_name: "{{ hostvars[groups['mongo'][0]]['ansible_eth0']['ipv4']['address'] }}", host_port: "{{ mongodb_net_port }}", host_type: replica } - { host_name: "{{ ho

我在Ansible playbook中有一个变量,我需要填充来自主机的信息。如果我以静态方式填充它:

mongodb_replication_params:
  - { host_name: "{{ hostvars[groups['mongo'][0]]['ansible_eth0']['ipv4']['address'] }}", host_port: "{{ mongodb_net_port }}", host_type: replica }
  - { host_name: "{{ hostvars[groups['mongo'][1]]['ansible_eth0']['ipv4']['address'] }}", host_port: "{{ mongodb_net_port }}", host_type: replica }
  - { host_name: "{{ hostvars[groups['mongo'][2]]['ansible_eth0']['ipv4']['address'] }}", host_port: "{{ mongodb_net_port }}", host_type: replica }
它将以正确的json格式存储:

[
    {
        "host_name": "172.31.xx.xxx", 
        "host_port": 27017, 
        "host_type": "replica"
    }, 
    {
        "host_name": "172.31.xx.xxx", 
        "host_port": 27017, 
        "host_type": "replica"
    }, 
    {
        "host_name": "172.31.xx.xxx", 
        "host_port": 27017, 
        "host_type": "replica"
    }
]
但是,我需要递归地执行它。我试过循环:

它存储在字符串中,而不是json中:

- { hostname: \"172.31.xx.xxx\", host_port: \"27017\", host_type: replica }\n  - { hostname: \"172.31.xx.xxx\", host_port: \"27017\", host_type: replica }\n  - { hostname: \"172.31.xx.xxx\", host_port: \"27017\", host_type: replica }\n
我不知道Jinja2语句需要做什么修改。或者可能有一些可以使用的Ansible模块。请帮忙,欢迎任何建议


编辑:关于变量mongodb\u replication\u params的使用方法,请参考本节的用法递归是什么意思?比如,在循环中,如我的Jinja2示例中,缺少上下文-您在哪里定义此变量?为什么将它们定义为YAML,然后说它是JSON?若您需要在运行时构造复杂变量,请参阅“其他问题”。@KonstantinSuvorov已编辑以包含对MongoDB ansible playbook的引用。mongodb_复制_参数是在剧本中定义的变量。你对其他问题的回答似乎是可行的,我会研究一下。你说的递归是什么意思?比如说,在一个循环中,就像在我的Jinja2例子中,缺少上下文——你在哪里定义这个变量?为什么将它们定义为YAML,然后说它是JSON?若您需要在运行时构造复杂变量,请参阅“其他问题”。@KonstantinSuvorov已编辑以包含对MongoDB ansible playbook的引用。mongodb_复制_参数是在剧本中定义的变量。你对其他问题的回答似乎可行,我会研究一下。
- { hostname: \"172.31.xx.xxx\", host_port: \"27017\", host_type: replica }\n  - { hostname: \"172.31.xx.xxx\", host_port: \"27017\", host_type: replica }\n  - { hostname: \"172.31.xx.xxx\", host_port: \"27017\", host_type: replica }\n