如何使用Ansible修改JSON文件中指定块的version键值
Ansible修改JSON指定块version字段实现方案
你给出的JSON片段需补全外层{}为合法JSON格式后,可通过Ansible原生模块安全修改,不会误改动未指定的块内容,具体实现如下:
方案一:JSON结构解析修改(推荐,无正则匹配误差)
直接解析JSON为字典结构修改,完全保留原有未指定字段的值:
--- - name: 更新JSON指定块version值 hosts: 你的目标主机组 vars: # 配置需要修改的块名和对应新版本号,按需增减即可 update_config: abc: "4.0.0-4" def: "4.0.0-4" json_file_path: "/替换为你的sample.json实际路径" tasks: - name: 读取JSON文件内容 ansible.builtin.slurp: src: "{{ json_file_path }}" register: raw_json_file - name: 转换JSON为可操作字典 ansible.builtin.set_fact: json_content: "{{ raw_json_file.content | b64decode | from_json }}" - name: 批量更新指定块的version字段 ansible.builtin.set_fact: json_content: "{{ json_content | combine({item.key: json_content[item.key] | combine({'version': item.value})}, recursive=True) }}" loop: "{{ update_config | dict2items }}" when: item.key in json_content - name: 写回修改后的JSON文件 ansible.builtin.copy: content: "{{ json_content | to_nice_json(indent=8) }}" dest: "{{ json_file_path }}"
- 可通过调整
to_nice_json的indent参数匹配原有文件的缩进格式 - 不在
update_config列表内的块(如示例中的ghi)所有字段完全保持不变
方案二:正则匹配修改(适用于非合法JSON片段场景)
如果你的文件确实是无外层{}的JSON片段,可使用正则精准匹配替换指定块的version值:
- name: 正则替换指定块version值 ansible.builtin.lineinfile: path: "/替换为你的sample.json实际路径" regexp: '(^\s*"{{ item }}":\s*{[^{}]*"version":\s*")[^"]*(".*)$' line: '\g<1>4.0.0-4\g<2>' backrefs: yes loop: - abc - def
内容的提问来源于stack exchange,提问作者JavaSeeker
相关产品推荐
相关产品推荐

