ansible - 从字典列表中加入成对的属性

ansible - join pairs of attributes from list of dictionaries

我有一个词典列表

myhosts:
  - {hostname: aaa, port: 1111}
  - {hostname: bbb, port: 2222}

我想得到一个包含连接的 host:port 对的字符串,就像这样

result = "aaa:1111, bbb:2222"

谢谢

编辑:yaml - 在冒号后添加空格

注意:键和值之间需要一个 space (hostname: aaa 而不是 hostname:aaa) 以获得您期望的数据结构。


你可以这样做:

- hosts: localhost
  vars:
    myhosts:
      - {hostname: aaa, port: 1111}
      - {hostname: bbb, port: 2222}

  tasks:
    - set_fact:
        mylist: >-
          {{ mylist + ["{hostname}:{port}".format(**item)] }}
      vars:
        mylist: []
      loop: "{{ myhosts }}"

    - debug:
        var: mylist

以上剧本产生以下输出:


PLAY [localhost] ***************************************************************

TASK [Gathering Facts] *********************************************************
ok: [localhost]

TASK [set_fact] ****************************************************************
ok: [localhost] => (item={'hostname': 'aaa', 'port': 1111})
ok: [localhost] => (item={'hostname': 'bbb', 'port': 2222})

TASK [debug] *******************************************************************
ok: [localhost] => {
    "mylist": [
        "aaa:1111",
        "bbb:2222"
    ]
}

PLAY RECAP *********************************************************************
localhost                  : ok=3    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0