2

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"
            }
        },
6
  • 1
    in dict, you cant rename a key, you have to create new key and remove old key so i dont see code in json_modify.py to remove key, you could update..so you have to recreate the part of update ip_configurations.0.. could you show the content of azure_network_interface_info ? Commented Jul 25, 2022 at 16:24
  • Updated the question with azure_network_interface_info. Commented Jul 25, 2022 at 16:42
  • Yea I need a way to update the json_modify.py so I could remove public_ip_address and add public_ip_address_name. Commented Jul 25, 2022 at 16:43
  • is it an obligation to remove the old key? Commented Jul 25, 2022 at 16:49
  • yea I need to remove the old key. Can't have both Commented Jul 25, 2022 at 16:50

1 Answer 1

2

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
                            }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.