'All combination of 2 lists in ansible
I have 2 variables as a list in ansible
host_list:
    - 1.1.1.1
    - 2.2.2.2
port_list:
    - 443
    - 80
and I want to get the 3rd variable as a list of lists:
all_comb = [[1.1.1.1, 443], [1.1.1.1, 80], [2.2.2.2, 443], [2.2.2.2, 80]]
How can i get it in Ansible?
Solution 1:[1]
you can use the with_nested or a query('nested', listA, listB) loop, see both implementations below:
with_nested:
- name: merge lists
  set_fact:
    merged_list: "{{ merged_list|default([]) + [item] }}"
  with_nested:
  - "{{ host_list }}"
  - "{{ port_list }}"
- name: display result
  debug:
    var: merged_list
with query:
- name: merge lists
  set_fact:
    merged_list: "{{ merged_list|default([]) + [item] }}"
  loop: "{{ query('nested', host_list, port_list) }}"
- name: display result
  debug:
    var: merged_list
result of the latter:
PLAY [localhost] ******************************************************************************************************************************************************************************************************
TASK [merge lists] ****************************************************************************************************************************************************************************************************
ok: [localhost] => (item=[u'1.1.1.1', 443])
ok: [localhost] => (item=[u'1.1.1.1', 80])
ok: [localhost] => (item=[u'2.2.2.2', 443])
ok: [localhost] => (item=[u'2.2.2.2', 80])
TASK [display result] *************************************************************************************************************************************************************************************************
ok: [localhost] => {
    "merged_list": [
        [
            "1.1.1.1", 
            443
        ], 
        [
            "1.1.1.1", 
            80
        ], 
        [
            "2.2.2.2", 
            443
        ], 
        [
            "2.2.2.2", 
            80
        ]
    ]
}
cheers
Solution 2:[2]
Use product filter
all_comb: "{{ host_list|product(port_list) }}"
gives
all_comb:
  - [1.1.1.1, 443]
  - [1.1.1.1, 80]
  - [2.2.2.2, 443]
  - [2.2.2.2, 80]
    					Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source | 
|---|---|
| Solution 1 | ilias-sp | 
| Solution 2 | 
