如何让Ansible执行Bash脚本时输出保留换行格式?
解决Ansible debug模块输出脚本stdout换行杂乱的问题
问题根源
Ansible注册脚本执行结果后,stdout字段会将脚本输出中的实际换行符转义为字符串\n,直接用debug输出stdout时,这些转义字符会被原样显示,导致排版混乱。
解决方法
方法1:利用stdout_lines循环输出
Ansible会自动将stdout按换行分割为列表stdout_lines,循环输出每个列表元素即可实现整齐的换行排版:
# 假设已存在的脚本执行注册步骤 - name: Execute OpenSSL check script script: OpenSSL_p.sh register: results # 修改后的debug输出部分 - name: Print formatted script output debug: msg: "{{ line }}" loop: "{{ results.stdout_lines }}" loop_control: label: "" # 移除循环序号标签,让输出更整洁
方法2:用过滤器替换转义换行符
如果希望一次性输出所有内容并保留换行,可使用replace过滤器将转义的\n替换为实际换行符:
- name: Show formatted output debug: msg: "{{ results.stdout | replace('\\n', '\n') }}"
方法3:直接输出stdout_lines(简洁版)
若接受每行前带列表符号,也可直接输出stdout_lines变量:
- name: Print script output debug: var: results.stdout_lines
效果对比
- 原杂乱输出:
Line1\nLine2\nLine3 - 修改后整齐输出:
Line1 Line2 Line3
内容的提问来源于stack exchange,提问作者vijayedm
相关产品推荐
相关产品推荐

