Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ansible – join pairs of attributes from list of dictionaries

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"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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   
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading