Ansible:将两个列表转换为键、值dict

Ansible:将两个列表转换为键、值dict,ansible,Ansible,我有两个列表作为set_fact,我想创建一个dict 我正在运行ansible 2.8 我有如下清单1 "inventory_devices": [ "device0", "device1" ] 和清单2如下所示 "inventory_ips": [ "10.1.1.1", "10.1.1.2" ] 我想得到一个像这样的输出 "inventory_dict": [ "device0": "10.1.1.1",

我有两个列表作为set_fact,我想创建一个dict

我正在运行ansible 2.8 我有如下清单1

  "inventory_devices": [
        "device0", 
        "device1" 
    ]
和清单2如下所示

"inventory_ips": [
    "10.1.1.1", 
    "10.1.1.2" 
]
我想得到一个像这样的输出

"inventory_dict": [
    "device0": "10.1.1.1",
    "device1": "10.1.1.2"
]

谢谢。

这是要完成的任务,
在下面的PB中填充组合var

---
- hosts: localhost
  gather_facts: false
  vars:
    inventory_devices:
      - device0
      - device1
    inventory_ips:
      - 10.1.1.1
      - 10.1.1.2

  tasks:
    - name: populate combined var
      set_fact:
        combined_var: "{{ combined_var|default({}) | combine({ item.0: item.1 }) }}"
      loop: "{{ query('together', inventory_devices, inventory_ips) }}"

    - name: print combined var
      debug:
        var: combined_var
结果:

TASK [print combined var] **********************************************************************************************************************************************************************************************
ok: [localhost] => {
    "combined_var": {
        "device0": "10.1.1.1",
        "device1": "10.1.1.2"
    }
}

希望它有帮助

您可以完全使用jinja2使用

要获得组合其他列表元素的列表,请使用zip

- name: give me list combo of two lists
  debug:
    msg: "{{ [1,2,3,4,5] | zip(['a','b','c','d','e','f']) | list }}"

与上面提到的items2dict过滤器的输出类似,这些过滤器可以是 用于构造一个
命令

{{ dict(keys_list | zip(values_list)) }}
zip
过滤器按顺序组合成对列表中的项目,而
dict
结构则根据成对列表创建字典

inventory_dict: "{{ dict(inventory_devices | zip(inventory_ips)) }}"

你已经尝试了什么来获得你的结果?在这篇文章的底部提供。我尝试了下面的方法。任务-名称:创建库存列表集合\u事实:库存列表:{{inventory\u var | default({}){124;合并({item.0}:{{item.1}}}}}}}}和\u在一起:-库存设备-库存IP我发现了我的错误。谢谢。这是一个非常棒的命令,但我不知道zip命令是做什么的?它需要两个列表,并将其中的项目组合成一对,每对一个,组成一个新的列表:列表列表。