我的任务是修改 JSON 文件中连接器的值,如下所示:
{
"school": [
{
"class": "class1",
"properties": {
"pupil": {
"name": "Mya",
"age": "8"
}
}
},
{
"class": "class2",
"properties": {
"pupil": {
"name": "Mya",
"age": "8"
}
}
}
]
}
如何创建ansible playbook仅为“class1”中的学生“姓名”和“年龄”设置新值?我期望结果如下。非常感谢您的帮助!
{
"school": [
{
"class": "class1",
"properties": {
"pupil": {
"name": "Jane",
"age": "9"
}
}
},
{
"class": "class2",
"properties": {
"pupil": {
"name": "Mya",
"age": "8"
}
}
}
]
}
update_fact
模块 – 更新当前设置的事实
一个最小的示例手册
---
- hosts: localhost
become: false
gather_facts: false
tasks:
- include_vars:
file: file.json
name: classes
- debug:
msg: "{{ classes }}"
- name: Update the fact
ansible.utils.update_fact:
updates:
- path: classes.school[0].properties.pupil.name
value: Jane
- path: classes.school[0].properties.pupil.age
value: 9
register: updated
- debug:
msg: "{{ updated.classes }}"
- copy:
dest: updated.file.json
content: "{{ updated.classes | to_nice_json(indent=4) }}"
将导致
所请求的输出TASK [include_vars] ******
ok: [localhost]
TASK [debug] *************
ok: [localhost] =>
msg:
school:
- class: class1
properties:
pupil:
age: '8'
name: Mya
- class: class2
properties:
pupil:
age: '8'
name: Mya
TASK [Update the fact] ***
changed: [localhost]
TASK [debug] *************
ok: [localhost] =>
msg:
school:
- class: class1
properties:
pupil:
age: 9
name: Jane
- class: class2
properties:
pupil:
age: '8'
name: Mya
TASK [copy] **************
changed: [localhost]
以及
的文件内容{
"school": [
{
"class": "class1",
"properties": {
"pupil": {
"age": 9,
"name": "Jane"
}
}
},
{
"class": "class2",
"properties": {
"pupil": {
"age": "8",
"name": "Mya"
}
}
}
]
}