You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Ansible无额外字符打印文件内容?类似Linux的cat命令

实现Ansible类似cat命令的纯净文件内容输出

问题场景

需要在Ansible Playbook中像Linux cat命令一样无额外字符地打印文件内容。现有文件/tmp/report-2023-10-19.html.txt内容如下:

server1 : The D:\ drive size is WRONG! Expected drive size: '1009'. Current size is: 100
server2 : The D:\ drive size is WRONG! Expected drive size: '1009'. Current size is: 100
server3 : The C:\ drive size is WRONG! Expected drive size: '12899'. Current size is: 126.51
server4 : The C:\ drive size is WRONG! Expected drive size: '12899'. Current size is: 126.51

原尝试的任务使用debug模块结合splitlines(),输出带有引号、逗号等多余字符:

- name: Display all findings
  debug:
   var: "file_content"
  vars:
   file_content: "{{ lookup('file', '/tmp/{{ reportfile }}.txt').splitlines() }}"
  delegate_to: localhost
  run_once: true
  when: num_lines.stdout | int > 0
  tags: always

输出结果包含冗余格式:

ok: [vmstfsh1 -> localhost] => {
    "file_content": [
        " server1 : The D:\\ drive size is WRONG! Expected drive size: '1009'. Current size is: 100 ",
        "",
        " server2 : The D:\\ drive size is WRONG! Expected drive size: '1009'. Current size is: 100 ",
        "",
        " server3 : The C:\\ drive size is WRONG! Expected drive size: '12899'. Current size is: 126.51 ",
        "",
        " server4 : The C:\\ drive size is WRONG! Expected drive size: '12899'. Current size is: 126.51"
    ]
}

解决方案

方法1:直接输出文件原始内容

使用debug模块的msg参数,直接输出lookup获取的文件原始内容,不进行splitlines()处理,Ansible会自动解析换行符:

- name: Display file content like cat
  debug:
    msg: "{{ lookup('file', '/tmp/' ~ reportfile ~ '.txt') }}"
  delegate_to: localhost
  run_once: true
  when: num_lines.stdout | int > 0
  tags: always

注意:变量拼接使用~而非嵌套双大括号,避免语法问题。

方法2:直接执行cat命令

通过command模块在目标主机(此处为localhost)执行cat命令,注册输出后打印:

- name: Execute cat command
  command: cat "/tmp/{{ reportfile }}.txt"
  register: cat_result
  delegate_to: localhost
  run_once: true
  when: num_lines.stdout | int > 0
  tags: always
  changed_when: false  # 标记任务为未变更,避免影响playbook状态

- name: Print cat output
  debug:
    msg: "{{ cat_result.stdout }}"
  delegate_to: localhost
  run_once: true
  when: num_lines.stdout | int > 0
  tags: always

方法3:使用stdout_callback简化输出(可选)

如果希望全局简化输出格式,可以临时设置ANSIBLE_STDOUT_CALLBACK=debug环境变量运行playbook,配合方法1或2使用,能进一步减少冗余的任务状态前缀:

ANSIBLE_STDOUT_CALLBACK=debug ansible-playbook your_playbook.yml

内容的提问来源于stack exchange,提问作者jeszi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 01:57:41