Ansible Dictionary Subelement – How to Access Subelement Values

ansibleansible-playbook

Here's my playbook

- name: Host's luns
  debug:
    msg: "{{ luns }}"
  vars:
    luns: "{{ ansible_facts.lvm.pvs }}"

And the output for this is

TASK [Luns del vg] ************************************************************
ok: [awxworker_rhel6] => {
    "msg": {
        "/dev/sda2": {
            "free_g": "20.72",
            "size_g": "79.72",
            "vg": "vg00"
        },
        "/dev/sdb1": {
            "free_g": "3.99",
            "size_g": "4.99",
            "vg": "vg01"
        },
        "/dev/sdc1": {
            "free_g": "0.99",
            "size_g": "4.99",
            "vg": "vg02"
        },
        "/dev/sdd1": {
            "free_g": "4.99",
            "size_g": "4.99",
            "vg": "vg01"
        }
    }
}

I need to get the luns of a matched vg

Ej: "The vg01 luns are: /dev/sdb1 /dev/sdd1"

I have tried this beetwen other ways

- name: Luns del VG
  set_fact:
    vg_luns: "{{ item }}"
  with_items: "{{ ansible_facts.lvm.pvs }}"
    vars:
      VGname: "{{ VG }}"
  when: ansible_facts.lvm.pvs.vg_luns.vg == VGname
  
- name: Print VG's luns
  debug:
    msg:
      - "The {{ VGname }} luns are: {{ vg_luns }}"

VG is an extravariable where I put the matched VGname

$ ansible-playbook -i proyects/Inventory/awx_hosts -l testhost getvgluns.yml -e VG=vg01

Hope you can help

Thanks in advance!

Best Answer

Create a dictionary of the groups. For example

  - set_fact:
      vgs: "{{ vgs|d({})|
               combine({item.0: item.1|
                                map(attribute='key')|
                                list}) }}"
    loop: "{{ luns|dict2items|groupby('value.vg') }}"

gives

  vgs:
    vg00:
    - /dev/sda2
    vg01:
    - /dev/sdb1
    - /dev/sdd1
    vg02:
    - /dev/sdc1

Then the selection is trivial

    - debug:
        msg: "The {{ VG }} luns are: {{ vgs[VG]|join(' ') }}"

gives the message

shell> ansible-playbook playbook.yml -e VG=vg01

  msg: 'The vg01 luns are: /dev/sdb1 /dev/sdd1'