【问题标题】:construct dict from 3 lists using Ansible使用 Ansible 从 3 个列表中构造 dict
【发布时间】:2021-06-06 00:45:57
【问题描述】:

我成功地构造了如下列表的变量:

TASK [get hostname] *****************************************
Sunday 07 March 2021  22:57:44 -0500 (0:00:00.254)       0:00:08.625 ********** 
ok: [ansiblehost] => {
    "varmachine": [
        "machine1", 
        "machine2", 
        "machine3"
    ]
}
TASK [Ostype] ***************
Sunday 07 March 2021  22:57:44 -0500 (0:00:00.065)       0:00:08.691 ********** 
ok: [ansiblehost] => {
    "varosname": [
        "Red Hat Enterprise Linux 7 (64-bit)", 
        "Red Hat Enterprise Linux 8 (64-bit)", 
        "windows Server 2016 (64-bit)"
    ]
}
TASK [domaines] **********************************
Sunday 07 March 2021  22:57:44 -0500 (0:00:00.084)       0:00:08.776 ********** 
ok: [ansiblehost] => {
    "domainevar": [
        "example1.com", 
        "example2.com", 
        "example3.com"
    ]
}

所以现在我想使用以前的变量列表生成 dict 列表:varmachine、varosname 和 domainevar,如下所示:

[{"name":"machine1","OSname":"Red Hat Enterprise Linux 7 (64-bit)", "Domaine":example1.com}, {"name":"machine2","OSname":"Red Hat Enterprise Linux 8 (64-bit)", "Domaine":example2.com},
"name":"machine3","OSname":"windows Server 2016 (64-bit)", "Domaine":example3.com} ]

换句话说,有点像:

[{"name":varmachine[0],"OSname":varosname[0], "Domaine":domainevar[0]}, {"name":varmachine[1],"OSname":varosname[1], "Domaine":domainevar[1]},
"name":varmachine[2],"OSname":varosname[2], "Domaine":domainevar[2]} ]

【问题讨论】:

    标签: arrays json list dictionary ansible


    【解决方案1】:

    下面的任务完成了这项工作

        - set_fact:
            _list: "{{ _list|default([]) + [dict(_keys|zip(item))] }}"
          with_together:
            - "{{ varmachine }}"
            - "{{ varosname }}"
            - "{{ domainevar }}"
          vars:
            _keys: [name, OSname, Domaine]
    

    给予

      _list:
      - Domaine: example1.com
        OSname: Red Hat Enterprise Linux 7 (64-bit)
        name: machine1
      - Domaine: example2.com
        OSname: Red Hat Enterprise Linux 8 (64-bit)
        name: machine2
      - Domaine: example3.com
        OSname: windows Server 2016 (64-bit)
        name: machine3
    

    【讨论】:

      猜你喜欢
      • 2022-11-17
      • 1970-01-01
      • 1970-01-01
      • 2018-07-07
      • 1970-01-01
      • 1970-01-01
      • 2021-06-22
      • 1970-01-01
      相关资源
      最近更新 更多