Home > database >  Change JSON key name using json_modify.py
Change JSON key name using json_modify.py

Time:07-26

How can I change JSON key name using json_modify.py?

I have the following array and I want to change the public_ip_address to 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"
                                    }
                                ],

Here is an example of how I can use json_modify but I'm not sure how to change the key.

  - 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 

Here is the facts of 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"
            }
        },

CodePudding user response:

ok i have found a solution is to modify the module in your library folder: i have added a new funtion renamekey and the content of old key is automatically added to the new key

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 to test:

- 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

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
                            }
  • Related