使用Ansible将新的键值添加到json文件中 [英] Add a new key-value to a json file using Ansible
问题描述
我正在使用Ansible为我的应用程序VM自动化一些配置步骤,但是很难将新的键值插入到远程主机上的现有json文件中.
I'm using Ansible to automate some configuration steps for my application VM, but having difficult to insert a new key-value to an existing json file on the remote host.
说我有这个json文件:
Say I have this json file:
{
"foo": "bar"
}
我想插入一个新的键值对以使文件变为:
And I want to insert a new key value pair to make the file become:
{
"foo": "bar",
"hello": "world"
}
由于json格式不是基于行的,因此我从选项中排除了lineinfile
模块.另外,我不希望使用任何外部模块. Google一直在给我一些示例来展示如何读取json文件,但是没有任何有关更改json值并将其写回到文件的内容.非常感谢您的帮助!
Since json format is not line based, I'm excluding lineinfile
module from my options. Also, I would prefer not to use any external modules. Google keeps giving me examples to show how to read json file, but nothing about change json values and write them back to file. Really appreciate your help please!
推荐答案
由于文件为json格式,因此您可以将文件导入变量,附加所需的多余key:value对,然后写回文件系统.
since the file is of json format, you could import the file to a variable, append the extra key:value pairs you want, and then write back to the filesystem.
这是一种实现方法:
---
- 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
更新:
随着OP更新,代码应可用于远程主机,在这种情况下,我们不能使用included_vars
或查找.我们可以使用slurp
模块.
as OP updated, the code should work towards remote host, in this case we cant use included_vars
or lookups. We could use the slurp
module.
NEW 代码:
---
- 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
希望有帮助
这篇关于使用Ansible将新的键值添加到json文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!