如何使用Ansible对比两个JSON文件并将基于第二个文件的差异写入新文件
Ansible实现两个YAML/JSON文件差异提取方案
实现逻辑
- 先将两个待比对文件加载为Ansible字典变量
- 遍历字典键筛选出值不一致的键值对
- 将符合要求的差异内容写入目标文件
完整Playbook示例
--- - name: 提取两个YAML文件的差异并写入新文件 hosts: localhost gather_facts: false tasks: # 读取file1.yml内容为字典变量 - name: 加载file1.yml内容 ansible.builtin.include_vars: file: file1.yml name: file1_content # 读取file2.yml内容为字典变量 - name: 加载file2.yml内容 ansible.builtin.include_vars: file: file2.yml name: file2_content # 筛选出两个字典中值不同的键值对(取file2的新值) - name: 比对并提取差异内容 ansible.builtin.set_fact: diff_result: "{{ diff_result | default({}) | combine({item: file2_content[item]}) }}" loop: "{{ file2_content.keys() | list }}" when: file2_content[item] != file1_content[item] # 将差异结果写入file3.yml - name: 写入差异内容到file3.yml ansible.builtin.copy: content: "{{ diff_result | to_nice_yaml(indent=2) }}" dest: ./file3.yml
注意事项
- 若待比对文件为纯JSON格式,可将
to_nice_yaml替换为to_nice_json适配输出格式 - 若文件内容为非标准字典结构,可先用
ansible.builtin.slurp模块读取内容后手动转字典处理 - 上述逻辑默认取file2中的新值作为差异输出,完全匹配给出的期望结果要求
- 若待比对文件仅为键值对片段,可先在读取时补全外层结构后再做比对
内容的提问来源于stack exchange,提问作者Ashish
相关产品推荐
相关产品推荐

