I have a list of dictionaries
myhosts:
- {hostname:aaa, port:1111}
- {hostname:bbb, port:2222}
And I want to get a single string containing the joined host:port pairs, like this
result = "aaa:1111, bbb:2222"
Thanks
>Solution :
NB: You need a space between the key and value (hostname: aaa
instead of hostname:aaa) to get the data structure you expect.
You could do something like this:
- 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
The above playbook produces the following output:
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