Ansible jinja2 - how to format and flatten cartesian product?

Imagine I have the following inventory

[myservers]
127.0.0.1
192.168.0.6

And in my vars file, the following:

interesting_things:
  - name: alice
    port: 8080
  - name: bob
    port: 8181

How can I produce the following result?

127.0.0.1[8080],127.0.0.1[8181],192.168.0.6[8080],192.168.0.6[8181]

I tried getting the cartesian product, but came unstuck:

debug: msg="{{ lookup('cartesian', groups['myservers'], interesting_things | map(attribute='port')) }}"

This gave me the following, but I can't work out how to go any further.

{
    "msg": [
        [
            "127.0.0.1",
            8080
        ],
        [
            "127.0.0.1",
            8181
        ],
        [
            "192.168.0.6",
            8080
        ],
        [
            "192.168.0.6",
            8181
        ]
    ]
}

1 answer

  • answered 2018-03-13 22:33 techraf

    Building on what you already have:

    - name:
      set_fact:
        my_list: "{{ my_list|default([]) + [my_element] }}"
      vars:
        my_element: "{{ item[0] }}[{{ item[1] }}]"
      with_items:
        - "{{ lookup('cartesian', groups['myservers'], interesting_things | map(attribute='port')) }}"
    
    - debug:
        msg: "{{ my_list|join(',') }}"
    

    Result:

    "msg": "127.0.0.1[8080],127.0.0.1[8181],192.168.0.6[8080],192.168.0.6[8181]"