1

I have two lists:

 "list1": [
            "xxxx"
            "yyyyy",
            "yyyyy",
            "yyyyy",
        ]
 "list2": [
            "xxxx"
            "yyyyy",
            "yyyyy",
            "yyyyy",
        ]

I do a loop on list2 to add it to list1, it works but adds it in new line like this:

        "xxxx",
        "yyyyy",
        "yyyyy",
        "yyyyy,
        "xxxx",
        "yyyyy",
        "yyyyy",
        "yyyyy",

the loop I used

    set_fact:
      list1: "{{ list1 |default([]) + list2 }}"
    loop: "{{ list2 }}"

meanwhile expected result:

            "xxxxxxxx",
            "yyyyyyyyyy",
            "yyyyyyyyyy",
            "yyyyyyyyyy,

GenZ
  • 49
  • 4

1 Answers1

1

Given the mre data

  l1: [a, b, c]
  l2: [d, e, f]

Join the items on the lists. The expected result is

  l3: [ad, be, cf]

A: zip the lists and join the items. The expression below gives the expected result

  l3: "{{ l1|zip(l2)|map('join')|list }}"

Example of a complete playbook

- hosts: localhost

  vars:

    l1: [a, b, c]
    l2: [d, e, f]
    l3: "{{ l1|zip(l2)|map('join')|list }}"

  tasks:

    - debug:
        var: l3
Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63
  • This is a really simple and easy to understand minimal example for [Combining items from multiple lists: `zip`](https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html#combining-items-from-multiple-lists-zip-and-zip-longest) together [Data manipultaion - List comprehensions with `map('join')`](https://docs.ansible.com/ansible/latest/user_guide/complex_data_manipulation.html#loops-and-list-comprehensions). – U880D Nov 22 '22 at 12:28