How to join a list of strings in Ansible?

前端 未结 1 2031
臣服心动
臣服心动 2020-12-18 18:38

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

相关标签:
1条回答
  • 2020-12-18 18:47

    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"
      
    0 讨论(0)
提交回复
热议问题