How to combine two lists?

pawel7318 asked:

I have a task which uses with_subelements but it’s terrible slow for big list (especially that most of the elements has duplicates and I don’t need to run it multiple times for them).

So I’m looking for a way to optimize it somehow. I wish to get all unique elements from that list – let say settings in the example below:

inventory:

my_list:
  - { name: foo, settings: ['x', 'y', 'z'] }      
  - { name: bar, settings: ['x', 'y', 'q', 'w'] }

tasks:

- name: get all settings
  set_fact:
    all_settings="{{ my_list|map(attribute='settings')|list }}"

- name: show results
  debug:
    var=all_settings

results:

"var": {
        "all_settings": [
            [
                "x",
                "y",
                "z"
            ],
            [
                "x",
                "y",
                "q"
                "w"
            ]
        ]
    }

I stuck at this point. How can I combine those list together ?

I’m looking for a way to get ['x', 'y', 'z', 'q', 'w']

My answer:


You need to use a union.

Off the top of my head:

all_settings="{{ foo|map(attribute='settings')|union(bar|map(attribute='settings')) }}"

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.