Preserve format of the file while printing in Ansible

Viewed 289

Below is my playbook to print the file.

I used couple of approaches but the file is not printed as is i.e. the new line formatting is gone when ansible prints the file contents.

  - name: List startup files
    shell: cat /tmp/test.txt
    register: readws

  - debug:
      msg: "/tmp/test.txt on {{ inventory_hostname }} is: {{ readws.stdout_lines }}"

  - debug:
      msg: "/tmp/test.txt on {{ inventory_hostname }} is: {{ lookup('file', '/tmp/test.txt') }}"

cat /tmp/test.txt 
i
m
good

Expected Ansible output:

TASK [debug] *****************************************************************************************
ok: [localhost] => {
    "msg": "/tmp/test.txt on localhost is: 
i
m
good
"
}

Ansible output:

TASK [List startup files] ******************************************************************
changed: [localhost]

TASK [debug] *****************************************************************************************
ok: [localhost] => {
    "msg": "/tmp/test.txt on localhost is: [u'i', u'm ', u'good']"
}

TASK [debug] *****************************************************************************************
ok: [localhost] => {
    "msg": "/tmp/test.txt on localhost is: i\nm \ngood"
}

Can you please suggest ?

2 Answers

You cannot really get what you require (unless maybe if you change the output callback plugin...).

The closest you can get is by displaying a list of lines like in the following example:

 - name: Show file content
   vars:
     my_file: /tmp/test.txt
     msg_content: |-
       {{ my-file }} on localhost is:
       {{ lookup('file', my_file) }}
   debug:
     msg: "{{ msg_content.split('\n') }}"

This might help who might come looking for simpler way to display a file in ansible.

stdout_lines prints the file with reasonable formatting.


    - name: display the file needed
      shell: cat /tmp/test.txt
      register: test_file

    - debug:
        var: test_file.stdout_lines
Related