Ansible循环输出格式问题:如何将单行结果按行拆分显示
解决Ansible Playbook输出换行问题
你当前的debug任务把命令输出都挤在一行,是因为用msg格式化列表时,Ansible会将列表转为带转义字符的字符串,而非解析换行。以下是几种可行的解决方法:
方法1:直接输出变量(推荐)
用debug模块的var参数替代msg,Ansible会自动将stdout_lines的每行内容展开显示:
- name: Output the results debug: var: mq_channel_output.results | map(attribute='stdout_lines') | list
方法2:遍历并拼接换行符
通过loop遍历每个结果,用join('\n')将stdout_lines的列表元素转为带换行的字符串:
- name: Output the results debug: msg: "{{ item | join('\n') }}" loop: "{{ mq_channel_output.results | map(attribute='stdout_lines') | list }}"
方法3:直接使用stdout属性
如果不需要单独处理每行,也可以直接调用stdout属性(它本身就是带换行符的完整字符串):
- name: Output the results debug: msg: "{{ item.stdout }}" loop: "{{ mq_channel_output.results }}"
效果对比
- 原输出(一行带转义符):
"5724-H72 (C) Copyright IBM Corp. 1994, 2022.\nStarting MQSC for queue manager MQ310.\n\n\n 1 : dis chs(*)\nAMQ8420I: Channel Status not found.\nOne MQSC command read.\nNo commands have a syntax error.\nOne valid MQSC command could not be processed."
- 优化后输出(每行单独显示):
5724-H72 (C) Copyright IBM Corp. 1994, 2022. Starting MQSC for queue manager MQ310. 1 : dis chs(*) AMQ8420I: Channel Status not found. One MQSC command read. No commands have a syntax error. One valid MQSC command could not be processed.
内容的提问来源于stack exchange,提问作者user3590915
相关产品推荐
相关产品推荐

