Ansible:一种替换 JSON 文件中文本的方法

问题描述 投票:0回答:1

我的任务是修改 JSON 文件中连接器的值,如下所示:

{
    "school": [
        {
            "class": "class1",
            "properties": {
                "pupil": {
                        "name": "Mya",
                        "age": "8"
                    }

                }
            },
        {
            "class": "class2",
            "properties": {
                "pupil": {
                        "name": "Mya",
                        "age": "8"
                        }
                }
        }
    ]
}

如何创建 Ansible 剧本以仅在

name
中为学生的
age
class1
设置新值?

我期望的结果如下。

{
    "school": [
        {
            "class": "class1",
            "properties": {
                "pupil": {
                        "name": "Jane",
                        "age": "9"
                    }

                }
            },
        {
            "class": "class2",
            "properties": {
                "pupil": {
                        "name": "Mya",
                        "age": "8"
                        }
                }
        }
    ]
}

非常感谢您的帮助!

json ansible
1个回答
0
投票

乍一看,一个可能的解决方案可能是使用

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"
                }
            }
        }
    ]
}

更多文档

类似问答

© www.soinside.com 2019 - 2024. All rights reserved.