使用Ansible将新的键值添加到json文件

fen*_*e87 9 json ansible

我正在使用Ansible为我的应用程序VM自动化一些配置步骤,但是很难将新的键值插入到远程主机上的现有json文件中。

说我有这个json文件:

{
  "foo": "bar"
}
Run Code Online (Sandbox Code Playgroud)

我想插入一个新的键值对以使文件变为:

{
  "foo": "bar",
  "hello": "world"
}
Run Code Online (Sandbox Code Playgroud)

由于json格式不是基于行的,因此我将lineinfile模块排除在选项之外。另外,我不希望使用任何外部模块。Google一直在给我一些示例来展示如何读取json文件,但是没有任何有关更改json值并将其写回到文件的内容。非常感谢您的帮助!

ili*_*-sp 9

由于文件是json格式,因此您可以将文件导入变量,添加所需的额外key:value对,然后写回文件系统。

这是一种方法:

---
- hosts: localhost
  connection: local
  gather_facts: false
  vars:

  tasks:
  - name: load var from file
    include_vars:
      file: /tmp/var.json
      name: imported_var

  - debug:
      var: imported_var

  - name: append more key/values
    set_fact:
      imported_var: "{{ imported_var | default([]) | combine({ 'hello': 'world' }) }}"

  - debug:
      var: imported_var

  - name: write var to file
    copy: 
      content: "{{ imported_var | to_nice_json }}" 
      dest: /tmp/final.json
Run Code Online (Sandbox Code Playgroud)

更新

随着OP更新,代码应可用于远程主机,在这种情况下,我们不能使用included_vars或查找。我们可以使用该slurp模块。

远程主机的代码:

---
- hosts: greenhat
  # connection: local
  gather_facts: false
  vars:

  tasks:
  - name: load var from file
    slurp:
      src: /tmp/var.json
    register: imported_var

  - debug:
      msg: "{{ imported_var.content|b64decode|from_json }}"

  - name: append more key/values
    set_fact:
      imported_var: "{{ imported_var.content|b64decode|from_json | default([]) | combine({ 'hello': 'world' }) }}"

  - debug:
      var: imported_var

  - name: write var to file
    copy: 
      content: "{{ imported_var | to_nice_json }}" 
      dest: /tmp/final.json
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你