Ansible Playbook将Junos命令输出保存为可读文件的问题
解决Junos设备Ansible命令输出保存异常问题
嘿,我帮你定位到问题啦!你遇到的文件内容只显示片段、格式异常的情况,是因为直接把整个showcmds注册变量写入文件了——这个变量其实是个包含执行状态、元数据等信息的复杂字典,不是纯粹的命令输出文本。咱们来调整一下Playbook,让它正确保存人类可读的输出:
修正后的完整Playbook
- name: Run a set of commands on Junos devices hosts: junos_devices vars: # 给输出文件名加上设备名和时间戳,避免多设备执行时覆盖文件 show_file: "junos_show_output_{{ inventory_hostname }}_{{ ansible_date_time.iso8601 }}.txt" tasks: - name: Create backups directory if it doesn't exist local_action: module: file path: backups state: directory - name: Execute show commands on Junos device junos_command: commands: - 'show route summary' - 'show bgp sum' output: text provider: "{{ netconf }}" register: showcmds - name: Save command output to human-readable file local_action: module: copy # 用分隔线拼接多个命令的输出,让文件结构更清晰 content: "{{ showcmds.stdout | join('\n\n---\n\n') }}" dest: "backups/{{ show_file }}" - name: Display show commands output debug: var: showcmds.stdout_lines
关键修改点说明
- 正确引用输出内容:
showcmds.stdout是一个列表,每个元素对应一条命令的纯文本输出。用| join('\n\n---\n\n')可以在不同命令的输出之间添加分隔线,确保写入文件的是纯粹的命令结果,不会混杂Ansible的元数据。 - 避免目录不存在的问题:新增了创建
backups目录的任务,防止因为目录不存在导致保存失败。 - 优化文件名:给
show_file变量加上设备名和时间戳,方便后续区分不同设备、不同时间的输出文件。 - 规范语法格式:把
commands从简写数组改成换行格式,debug模块的写法也更规范,提升Playbook的可读性和维护性。
这样调整后,你生成的文件就会完整保存所有命令的输出内容,格式和你在设备上直接执行命令看到的完全一致啦!
内容的提问来源于stack exchange,提问作者Gary Rubel
相关产品推荐
相关产品推荐

