在 Ansible 中打印时保留文件格式

Preserve format of the file while printing in Ansible

下面是我打印文件的剧本。

我使用了几种方法,但文件没有按原样打印,即当 ansible 打印文件内容时,换行格式消失了。

  - 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

预期的 Ansible 输出:

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

Ansible 输出:

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"
}

你能推荐一下吗?

您无法真正获得所需的东西(除非您更改输出回调插件...)。

最接近的方法是显示行列表,如下例所示:

 - 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') }}"

这可能会帮助那些可能会寻找更简单的方法来在 ansible 中显示文件的人。

stdout_lines 以合理的格式打印文件。


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

    - debug:
        var: test_file.stdout_lines