Dictionary 从ansible playbook中的主机组创建字典列表

Dictionary 从ansible playbook中的主机组创建字典列表,dictionary,ansible,Dictionary,Ansible,我想动态创建一个字典列表,如下所示: [ {'host': 'hostname1', 'id': 1}, {'host': 'hostname2', 'id': 2}, ] 并将其分配给我剧本中的一个变量 我正在使用的角色需要此变量 我的尝试如下: - hosts: - some-hosts vars: zk_hosts: [] tasks: - name: create my var set_fact: zk_hosts: "{{ z

我想动态创建一个字典列表,如下所示:

[ {'host': 'hostname1', 'id': 1}, {'host': 'hostname2', 'id': 2}, ]
并将其分配给我剧本中的一个变量

我正在使用的角色需要此变量

我的尝试如下:

- hosts:
   - some-hosts
  vars:
    zk_hosts: []
  tasks:
    - name: create my var
      set_fact:
        zk_hosts: "{{ zk_hosts + [ {'host': item.1, 'id': item.0} ] }}"
      with_indexed_items: "{{ groups.some-hosts }}"
但是,当我运行playbook时,我有以下警告:

 [WARNING]: While constructing a mapping from stack.yml, line 16, column 3, found a duplicate dict key (vars).  Using last defined value only.
这出戏中的错误:

fatal: [192.168.0.21]: FAILED! => {"failed": true, "msg": "ERROR! 'zk_hosts' is undefined"}
如果我在试图设置事实之前没有定义
zk_hosts
,我会得到一个错误,即变量未定义

我怎样才能解决这个问题


编辑

很容易修复,我刚刚在同一个任务中定义了
zk_hosts

  tasks:
    - name: create my var
      vars:
        zk_hosts: []
      set_fact:
        zk_hosts: "{{ zk_hosts + [ {'host': item.1, 'id': item.0} ] }}"
      with_indexed_items: "{{ groups.some-hosts }}"

无论如何,如果有一种不那么麻烦的方法可以达到同样的效果,请给出建议

您可以使用默认过滤器:

set_fact:
  zk_hosts: "{{ zk_hosts|default([]) + [ {'host': item.1, 'id': item.0} ] }}"
with_indexed_items: "{{ groups.some-hosts }}"