代码之家  ›  专栏  ›  技术社区  ›  fengye87

使用ansible向JSON文件添加新的键值

  •  5
  • fengye87  · 技术社区  · 6 年前

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

    假设我有这个JSON文件:

    {
      "foo": "bar"
    }
    

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

    {
      "foo": "bar",
      "hello": "world"
    }
    

    因为JSON格式不是基于行的,所以我不包括 lineinfile 我选项中的模块。另外,我不希望使用任何外部模块。谷歌一直在给我举例子来说明如何读取JSON文件,但并没有改变JSON值并将其写回文件。非常感谢你的帮助!

    2 回复  |  直到 6 年前
        1
  •  6
  •   ilias-sp    6 年前

    ---
    - 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
    

    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
    

    希望有帮助

        2
  •  0
  •   Rich Nahra    6 年前
     - name: update log
        copy:
          content: "{{ log | to_nice_json}}"
          dest: "{{ log_file }}"
        vars:
          log: "{{ (lookup('file', log_file) | from_json) + ([{'job': (build_id if build_id != '' else 'dev'), 'keystore': ks, 'timestamp': ansible_date_time.iso8601}]) }}"
          log_file: log/log.json
          build_id: "{{ lookup('ENV', 'BUILD_ID') }}"
        tags: log