更新时间:2023-11-23 23:22:10
由于文件是 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
希望能帮到你