Ansible获取Juniper配置如何直接保存为to_nice_json格式文件
解决方案
你可以直接通过Ansible内置的to_nice_json过滤器处理拉取到的配置内容,不需要调用外部工具,有两种常用实现方式:
方案1:直接处理模块返回值(无需临时文件)
juniper_junos_config模块执行后会在返回值的config字段中携带拉取到的配置内容,直接对该字段做JSON格式化后写入目标文件即可:
- name: 读取Juniper已提交的JSON配置 juniper_junos_config: provider: "{{ netconf }}" retrieve: "committed" format: "json" register: junos_config_result - name: 保存格式化后的JSON配置到目标文件 copy: content: "{{ junos_config_result.config | to_nice_json(indent=2) }}" dest: "{{ conf_file_json }}.json"
方案2:保留临时文件流程的改造方案
如果现有逻辑必须保留临时文件环节,可以读取临时文件内容后做格式转换再存储:
- name: Save device "json" config juniper_junos_config: provider: "{{ netconf }}" retrieve: "committed" format: "json" dest: "{{ temp_config_file }}" - name: 读取临时JSON文件并格式化后存储 copy: content: "{{ lookup('file', temp_config_file) | from_json | to_nice_json(indent=2) }}" dest: "{{ conf_file_json }}.json"
to_nice_json支持自定义参数,比如添加indent=4调整缩进为4空格,添加sort_keys=True开启键名排序,可根据需求自行调整。
内容的提问来源于stack exchange,提问作者chester
相关产品推荐
相关产品推荐

