ansible

How to use ansible.builtin.copy with content and ensure resulting file ends with a new line?


I am ensuring a file with a specific content is present on a Linux machine.

Neither of the tasks below resulted in a file that ends with with a newline:

- name: Write a file with content
  ansible.builtin.copy:
    content: "{{ files_content }}"
    dest: /tmp/foo.txt

- name: Write a file with content
  ansible.builtin.copy:
    content: "{{ files_content }}\\n"
    dest: /tmp/bar.txt

- name: Write a file with content
  ansible.builtin.copy:
    content: "{{ files_content }}\n"
    dest: /tmp/foobar.txt"

How can I make sure that the file ends with a newline character?

If there is no other way I guess I could use the task below.

- name: Write a file with content
  ansible.builtin.copy:
    content: | 
             {{ files_content }}
    dest: /tmp/foobar.txt"

But I am curious if I have to.


Solution

  • Q: "How can I make sure that the file ends with a newline character?"

    A: Just add the character to the variable content, the string during Templating (Jinja2).

    A minimal example playbook

    ---
    - hosts: localhost
      become: false
      gather_facts: false
    
      vars:
    
        CONTENT: 'test'
    
      tasks:
    
        - name: Write a file with content
          ansible.builtin.copy:
            content: "{{ CONTENT ~ '\n' }}"
            dest: test.txt
    

    will result into an outfile test.txt with the requested content.

    $ cat test.txt
    test
    $