访问字典子元素值

访问字典子元素值

这是我的剧本

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

输出如下

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"
        }
    }
}

我需要获取匹配的 vg 的 lun

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

我已经尝试过其他方法

- 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 是一个外部变量,我将匹配的 VGname

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

希望你能帮助

Thanks in advance!

答案1

创建群组字典。例如

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

给出

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

那么选择就很简单了

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

传达信息

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

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

答案2

无需 set_fact 或 Ansible 循环。将字典转换为列表并对其使用常规 Jinja 操作。

- debug:
    msg: "The {{ VG }} luns are: {{ ansible_facts.lvm.pvs | dict2items | selectattr('value.vg', 'equalto', VG) | map(attribute='key') | join(' ') }}"

相关内容