How to join a list of strings in Ansible?


In Ansible, I have a list of strings that I want to join with newline characters to create a string, that when written to a file, becomes a series of lines. However, when I use the join() filter, it works on the inner list, the characters in the strings, and not on the outer list, the strings themselves. Here’s my sample code:

I want to get output that looks like:

What I get instead is:

How do I properly concatenate a list of strings with the newline character?



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


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.


  • 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):

This Post Has One Comment

  1. Avatar

    join(‘\n’) is well and good, but just a wrning in that it does not add a newline to the end of the last entry.
    Which with newlines is generally preferred.

Leave a Reply