[Python] Transform Ansible list of dictionaries to dictionary

Discussão em 'Python' iniciado por Stack, Julho 27, 2025.

  1. Stack

    Stack Membro Participativo

    Many Ansible Modules return a set of objects. When these objects do not have a unique identifying attribute, the data is often returned as a list of dictionaries. For example, the built-in setup module returns mount points this way. (I omitted some attributes for better readability.)

    "ansible_mounts": [
    {
    "device": "/dev/sda1",
    "fstype": "vfat",
    "mount": "/boot/efi",
    "size_available": 202100736,
    "size_total": 209469440
    },
    {
    "device": "/dev/mapper/rootvg-rootlv",
    "fstype": "xfs",
    "mount": "/"
    },
    {
    "device": "/dev/mapper/rootvg-homelv",
    "fstype": "xfs",
    "mount": "/home"
    }
    ]


    I understand, that the device or mount entries do not necessarily need to be unique, so a list is the only structure that can always be constructed. But in my case, they are. So I would prefer this data structure instead.

    {
    "/boot/efi": {
    "device": "/dev/sda1",
    "fstype": "vfat",
    "size_available": 202100736,
    "size_total": 209469440
    },
    "/dev/mapper/rootvg-rootlv": {
    "fstype": "xfs",
    "mount": "/"
    },
    "/dev/mapper/rootvg-homelv": {
    "fstype": "xfs",
    "mount": "/home"
    }
    }


    Is there a combination of built-in filters that can easily transform one into the other? A filter plugin doing this can be written in a few lines of Python, though I was unable to find one on Ansible Galaxy. So before I upload one myself I would like to know if I am overlooking an obvious built-in solution.

    Continue reading...

Compartilhe esta Página