Ansible

訪問 dict 子元素值

  • September 7, 2021

這是我的劇本

- 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!

創建組的字典。例如

 - 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'

不需要 set_fact 或 Ansible 循環。將字典轉換為列表並對其使用正常的 Jinja 操作。

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

引用自:https://serverfault.com/questions/1076814