How to join a list of strings in Ansible?

Solution

join filter works on lists, so apply it to your list:

- name: Concatenate the public keys
  set_fact:
    my_joined_list: "{{ my_list | join('\n') }}"

Explanation

While my_list in your example is a list, when you use with_items, in each iterationitem is a string. Strings are treated as lists of characters, thus join splits them.

It’s like in any language: when you have a loop for i in (one, two, three) and refer to i inside the loop, you get only one value for each iteration, not the whole set.


Remarks

  • Don’t use debug module, but copy with content to have\n rendered as newline.

  • The way you create a list is pretty cumbersome. All you need is (quotation marks are also not necessary):

    - name: Create the list
      set_fact:
        my_list:
          - "One fish"
          - "Two fish"
          - "Red fish"
          - "Blue fish"