ansible,如何替换和过滤json数据?

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

我第一次尝试编写ansible代码来处理json。

我的 /home/ 中有一个文件,其中包含以下 json 数据。

这里是输入的json

  "acl": [
    {
      "browse": true,
      "create": false
    },
    {
      "browse": false,
      "create": true
    }
  ],
  "groups": [
    {
      "name": "abc",
      "location": "texas"
    },
    {
      "name": "def",
      "location": "austin"
    }
  ],
  "users": [
    {
      "name": "admin",
      "description": "administrator",
      "password": "windows2011"
    },
    {
      "name": "testuser",
      "description": "guest",
      "password": "testpassword"
    }
  ]
}

我想更新名称为 admin 的用户对象中的用户密码

因此输出文件已更新用户管理员的密码。输出文件应位于 /home/location 中,扩展名为 _updated.json。

输出的json应该是这样的

{
  "acl": [
    {
      "browse": true,
      "create": false
    },
    {
      "browse": false,
      "create": true
    }
  ],
  "groups": [
    {
      "name": "abc",
      "location": "texas"
    },
    {
      "name": "def",
      "location": "austin"
    }
  ],
  "users": [
    {
      "name": "admin",
      "description": "administrator",
      "password": "updatedpassword"
    },
    {
      "name": "testuser",
      "description": "guest",
      "password": "testpassword"
    }
  ]
}

到目前为止我写的ansible代码-

---
- name: Update admin user password in JSON file
  hosts: localhost
  gather_facts: no
  tasks:
    - name: Read the JSON file
      ansible.builtin.command:
        cmd: cat /home/conf.json
      register: json_content

谢谢你。

json ansible
1个回答
0
投票

您可以使用

template
模块并使用“变量插值”来输入您想要使用的密码。首先更新您的
conf.json
文件:

{
  "acl": [
    {
      "browse": true,
      "create": false
    },
    {
      "browse": false,
      "create": true
    }
  ],
  "groups": [
    {
      "name": "abc",
      "location": "texas"
    },
    {
      "name": "def",
      "location": "austin"
    }
  ],
  "users": [
    {
      "name": "admin",
      "description": "administrator",
      "password": "{{ admin_password }}"
    },
    {
      "name": "testuser",
      "description": "guest",
      "password": "testpassword"
    }
  ]
}

然后更新您的 Ansible 脚本以使用新密码替换变量:

---
- name: Update admin user password in JSON file
  hosts: localhost
  gather_facts: no
  vars:
    admin_password: 'updatedpassword'
  tasks:
    - name: Update the JSON configuration
      ansible.builtin.template:
        src: /home/conf.json
        dest: /home/updated_conf.json

https://docs.ansible.com/ansible/latest/collections/ansible/builtin/template_module.html

您也可以对

testuser
帐户执行相同的操作,将密码替换为
{{ testuser_password }}
,然后将变量和值添加到 Ansible 脚本中。

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