我一直在嘗試使用源 JSON 檔案中字典中的值更新目標 json 中字典中的值。以下是源和目標 JSON 檔案的示例:
源檔案:
[
{
"key": "MYSQL",
"value": "456"
},
{
"key": "RDS",
"value": "123"
}
]
目標檔案:
[
{
"key": "MYSQL",
"value": "100"
},
{
"key": "RDS",
"value": "111"
},
{
"key": "DB1",
"value": "TestDB"
},
{
"key": "OS",
"value": "EX1"
}
]
運行 Ansible playbook 后對目標檔案的期望:
[
{
"key": "MYSQL",
"value": "**456**"
},
{
"key": "RDS",
"value": "**123**"
},
{
"key": "DB1",
"value": "TestDB"
},
{
"key": "OS",
"value": "EX1"
}
]
以下是我迄今為止嘗試過的劇本,但這只會在硬編碼時更新值:
- hosts: localhost
tasks:
- name: Parse JSON
shell: cat Source.json
register: result
- name: Save json data to a variable
set_fact:
jsondata: "{{result.stdout | from_json}}"
- name: Get key names
set_fact:
json_key: "{{ jsondata | map(attribute='key') | flatten }}"
- name: Get Values names
set_fact:
json_value: "{{ jsondata | map(attribute='value') | flatten }}"
# Trying to update the destination file with only the values provided in source.json
- name: Replace values in json
replace:
path: Destination.json
regexp: '"{{ item }}": "100"'
replace: '"{{ item }}": "456"'
loop:
- value
主要目標是更新value在destination.json與value中提供source.json。
uj5u.com熱心網友回復:
在 Ansible 中,一對key/value傾向于使用過濾器dict2items和items2dict. 您的用例可以由這些過濾器處理。
這將是邏輯:
- 讀取兩個檔案
- 將兩個檔案轉換為字典,使用
dict2items - 結合兩個字典,
combine用過濾器 - 將字典轉換回串列
items2dict - 將 JSON 中的結果轉儲回檔案
鑒于劇本:
- hosts: localhost
gather_facts: no
tasks:
- shell: cat Source.json
register: source
- shell: cat Destination.json
register: destination
- copy:
content: "{{
destination.stdout | from_json | items2dict |
combine(
source.stdout | from_json | items2dict
) | dict2items | to_nice_json
}}"
dest: Destination.json
我們最終得到Destination.json包含:
[
{
"key": "MYSQL",
"value": "456"
},
{
"key": "RDS",
"value": "123"
},
{
"key": "DB1",
"value": "TestDB"
},
{
"key": "OS",
"value": "EX1"
}
]
uj5u.com熱心網友回復:
如果不知道目標檔案的結構,就很難使用正則運算式。
我建議您將目標檔案加載到變數中,進行更改并將變數的內容保存到檔案中。
此解決方案可以完成以下作業:
- hosts: localhost
tasks:
- name: Parse JSON
set_fact:
source: "{{ lookup('file', 'source.json') | from_json }}"
destination: "{{ lookup('file', 'destination.json') | from_json }}"
- name: create new json
set_fact:
json_new: "{{ json_new | d([]) ([item] if _rec == [] else [_rec]) | flatten }}"
loop: "{{ destination }}"
vars:
_rec: "{{ source | selectattr('key', 'equalto', item.key) }}"
- name: save new json
copy:
content: "{{ json_new | to_nice_json }}"
dest: dest_new.json
結果 -> dest_new.json:
ok: [localhost] => {
"msg": [
{
"key": "MYSQL",
"value": "456"
},
{
"key": "RDS",
"value": "123"
},
{
"key": "DB1",
"value": "TestDB"
},
{
"key": "OS",
"value": "EX1"
}
]
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/362936.html
標籤:json 列表 字典 能听懂的 ansible-2.x
上一篇:在這個字典中找不到最低的數值
