Search code examples
ansiblejinja2

Manipulating data in Ansible


My vm_info is below.

ok: [localhost] => {
"vm_info": {
    "results": [
        {
            "item": "AP",
            "vms": [
                {
                    "VM": "1"
                },
                {
                    "VM": "2"
                },
                {
                    "VM": "2"
                },
            ],
            "item": "US",
            "vms": [
                    {
                        "VM": "1"
                    },
                    {
                        "VM": "2"
                    },
                    {
                        "VM": "2"
                    },
                    ]
            }
        ]
    }
}

I want to add each item to each VM in Ansible and create new dictionary. My desired output:

"updated_vm": {
    "results": [
        {
            "item": "AP",
            "vms": [
                {
                    "VM": "1",
                    "item": "AP",
                },
                {
                    "VM": "2",
                    "item": "AP",
                },
                {
                    "VM": "3",
                    "item": "AP",
                },
            ],
            "item": "US",
            "vms": [
                    {
                        "VM": "1",
                        "item": "US"
                    },
                    {
                        "VM": "2",
                        "item": "US"
                    },
                    {
                        "VM": "2"
                        "item": "US"
                    },
                    ]
            }
        ]
    }
}

Is this even possible to add same level key inside another key?
Where I can find documentation to understand this?


Solution

  • Q: "Is this even possible to add same level key inside another key?"

    No and yes. It is not possible to change that result set, but possible to create a new one from with the necessary properties, see Alter Registered Variable and update_fact module – Update currently set facts.

    Q: "Where I can find documentation to understand this?"

    Since that is just basic algorithms and data structures, such is probably not directly documented or in the way you would expect, but you could start with Complex data manipulation, How to work with lists and dictionaries in Ansible or How to work with a list of dictionaries in Ansible, etc. ...