使用 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
模块.另外,我不想使用任何外部模块.谷歌一直给我例子来展示如何读取 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.
新远程主机代码:
---
- 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屋!