如何使用json_modify.py更改JSON键名?

我有以下数组,我想把public_ip_address改为public_ip_address_name.

                                "ip_configurations": [
                                    {
                                        "application_gateway_backend_address_pools": null,
                                        "application_security_groups": null,
                                        "load_balancer_backend_address_pools": null,
                                        "name": "Ubuntu915",
                                        "primary": true,
                                        "private_ip_address": "10.0.0.5",
                                        "private_ip_allocation_method": "Dynamic",
                                        "public_ip_address": "/subscriptions/123456/resourceGroups/cloud-shell-storage-centralindia/providers/Microsoft.Network/publicIPAddresses/Ubuntu-915-test",
                                        "public_ip_allocation_method": "Dynamic"
                                    }
                                ],

下面是一个如何使用json_modify的示例,但我不确定如何更改键.

  - json_modify:
      data: "{{ azure_network_interface_info }}"
      pointer: "/networkinterfaces/0/ip_configurations/0"
      action: update
      update: { "public_ip_address": "testing" }
    register: azure_network_interface_info_modified 

以下是azure_network_interface_info个事实:

        {
            "hosts": {
                "localhost": {
                    "_ansible_no_log": null,
                    "action": "azure_rm_networkinterface_info",
                    "changed": false,
                    "invocation": {
                        "module_args": {
                            "ad_user": null,
                            "adfs_authority_url": null,
                            "api_profile": "latest",
                            "auth_source": "auto",
                            "cert_validation_mode": null,
                            "client_id": null,
                            "cloud_environment": "AzureCloud",
                            "log_mode": null,
                            "log_path": null,
                            "name": "Ubuntu915",
                            "password": null,
                            "profile": null,
                            "resource_group": "cloud-shell-storage-centralindia",
                            "secret": null,
                            "subscription_id": null,
                            "tags": null,
                            "tenant": null
                        }
                    },
                    "networkinterfaces": [
                        {
                            "dns_servers": [],
                            "dns_settings": {
                                "applied_dns_servers": [],
                                "dns_servers": [],
                                "internal_dns_name_label": null,
                                "internal_fqdn": null
                            },
                            "enable_accelerated_networking": false,
                            "enable_ip_forwarding": false,
                            "id": "/subscriptions/123456/resourceGroups/cloud-shell-storage-centralindia/providers/Microsoft.Network/networkInterfaces/Ubuntu915",
                            "ip_configurations": [
                                {
                                    "application_gateway_backend_address_pools": null,
                                    "application_security_groups": null,
                                    "load_balancer_backend_address_pools": null,
                                    "name": "Ubuntu915",
                                    "primary": true,
                                    "private_ip_address": "10.0.0.5",
                                    "private_ip_allocation_method": "Dynamic",
                                    "public_ip_address": "/subscriptions/123456/resourceGroups/cloud-shell-storage-centralindia/providers/Microsoft.Network/publicIPAddresses/Ubuntu-915-test",
                                    "public_ip_allocation_method": null
                                }
                            ],
                            "location": "eastus",
                            "mac_address": "00-0D-3A-8C-CF-8C",
                            "name": "Ubuntu915",
                            "provisioning_state": "Succeeded",
                            "resource_group": "cloud-shell-storage-centralindia",
                            "security_group": "/subscriptions/123456/resourceGroups/cloud-shell-storage-centralindia/providers/Microsoft.Network/networkSecurityGroups/testing_testing_temp_123",
                            "subnet": "default",
                            "tags": null,
                            "virtual_network": {
                                "name": "testing-vm_group-vnet",
                                "resource_group": "testing-vm_group"
                            }
                        }
                    ]
                }
            },
            "task": {
                "duration": {
                    "end": "2022-07-25T16:39:01.551871Z",
                    "start": "2022-07-25T16:38:58.618111Z"
                },
                "id": "0242ac11-0002-08f0-de66-00000000000a",
                "name": "Get facts for one network interface"
            }
        },

推荐答案

好的,我发现一个解决方案是修改库文件夹中的模块:

from ansible.module_utils.basic import AnsibleModule

import json

try:
    import jsonpointer
except ImportError:
    jsonpointer = None


def main():
    module = AnsibleModule(
        argument_spec=dict(
            data=dict(required=True, type='dict'),
            pointer=dict(required=True),
            action=dict(required=True,
                        choices=['append', 'extend', 'update', 'renamekey']),
            update=dict(type='dict'),
            extend=dict(type='list'),
            append=dict(),
            renamekey=dict(type='list'),
        ),
        supports_check_mode=True,
    )

    if jsonpointer is None:
        module.fail_json(msg='jsonpointer module is not available')

    action = module.params['action']
    data = module.params['data']
    pointer = module.params['pointer']

    if isinstance(data, str):
        data = json.loads(str)

    try:
        res = jsonpointer.resolve_pointer(data, pointer)
    except jsonpointer.JsonPointerException as err:
        module.fail_json(msg=str(err))


    if action == 'append':
        res.append(module.params['append'])
    if action == 'extend':
        res.extend(module.params['extend'])
    elif action == 'update':
        res.update(module.params['update'])
    elif action == 'renamekey':
        oldkey = module.params['renamekey'][0]
        newkey = module.params['renamekey'][1]
        value = res[oldkey]  #get the value of oldkey
        res.pop(oldkey)      #delete the oldkey
        res.update({module.params['renamekey'][1]: value}) #add newkey with value saved

    module.exit_json(changed=True,
                     result=data)


if __name__ == '__main__':
    main()

要测试的 playbook :

- json_modify:
    data: "{{ azure_network_interface_info }}"
    pointer: "/networkinterfaces/0/ip_configurations/0"
    action: renamekey
    renamekey: ["public_ip_address", "public_ip_address_name"] #[oldkey, newkey]
  register: result

结果:

                        "ip_configurations": [
                            {
                                "application_gateway_backend_address_pools": null,
                                "application_security_groups": null,
                                "load_balancer_backend_address_pools": null,
                                "name": "Ubuntu915",
                                "primary": true,
                                "private_ip_address": "10.0.0.5",
                                "private_ip_allocation_method": "Dynamic",
                                "public_ip_address_name": "/subscriptions/123456/resourceGroups/test-rg/providers/Microsoft.Network/publicIPAddresses/Ubuntu915-publicIp",
                                "public_ip_allocation_method": null
                            }

Python相关问答推荐

Polars LazyFrame在收集后未返回指定的模式顺序

为什么tkinter框架没有被隐藏?

删除任何仅包含字符(或不包含其他数字值的邮政编码)的观察

对于一个给定的数字,找出一个整数的最小和最大可能的和

使用索引列表列表对列进行切片并获取行方向的向量长度

有症状地 destruct 了Python中的regex?

Streamlit应用程序中的Plotly条形图中未正确显示Y轴刻度

不允许访问非IPM文件夹

Django—cte给出:QuerySet对象没有属性with_cte''''

如何创建引用列表并分配值的Systemrame列

使用Openpyxl从Excel中的折线图更改图表样式

如何在Python中使用Iscolc迭代器实现观察者模式?

统计numpy. ndarray中的项目列表出现次数的最快方法

Pandas 数据帧中的枚举,不能在枚举列上执行GROUP BY吗?

在Django中重命名我的表后,旧表中的项目不会被移动或删除

获取git修订版中每个文件的最后修改时间的最有效方法是什么?

在我融化极点数据帧之后,我如何在不添加索引的情况下将其旋转回其原始形式?

Pandas数据框上的滚动平均值,其中平均值的中心基于另一数据框的时间

使用pyopencl、ArrayFire或另一个Python OpenCL库制作基于欧几里得距离的掩模

条件Python Polars cum_sum over a group,有更好的方法吗?