keys method for ansible

Viewed 60

I'm look for an simple way to create a list keys of a dictionary as one does in Python with the keys method but it seems this doesn't exist in Ansible. For example, below is the output of the setup module on a host.

"ansible_lvm": {
...
            "pvs": {
                "/dev/sda2": {
                    "free_g": "0",
                    "size_g": "8.81",
                    "vg": "rhel"
                },
                "/dev/sdb1": {
                    "free_g": "1.50",
                    "size_g": "3.00",
                    "vg": "bob"
                }
            },

The result I would like to achieve is to have the devices, dev/sda1 ..., in a list so that I can easily test to see if a device in the list of pvs or other operations on the list of keys. I know there are workarounds for about every case I have come up with but I feel like I'm missing something since it seems like something rather fundamental.

1 Answers

Simply transform your dict to a list and you will get its keys as in the following example:

---
- name: List of keys demo
  hosts: localhost
  gather_facts: false

  vars:
    "pvs": {
      "/dev/sda2": {
        "free_g": "0",
        "size_g": "8.81",
        "vg": "rhel"
      },
      "/dev/sdb1": {
        "free_g": "1.50",
        "size_g": "3.00",
        "vg": "bob"
      }
    }

  tasks:
    - name: "List keys"
      debug:
        msg: "{{ pvs | list }}"

which gives

PLAY [List of keys demo] ********************************************************************************************************************************************************************************************************************

TASK [List keys] ****************************************************************************************************************************************************************************************************************************
ok: [localhost] => {
    "msg": [
        "/dev/sda2",
        "/dev/sdb1"
    ]
}

PLAY RECAP **********************************************************************************************************************************************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
Related