簡體   English   中英

Ansible:作為條件遍歷字典中的列表

[英]Ansible: iterate over a list in dictionary as condition

我創建了一個角色來創建LVM VG,並使其完全等冪且具有故障證明功能,我想驗證PV是否存在且尚未定義VG。

角色/ LVM /瓦爾/ main.yml

---
lvm_vgs:
  - vg_name: drbdpool
    vg_pvs: "{{ vg_drbdpool_pvs }}"

host_vars /主機名

---
vg_drbdpool_pvs: ['sdc1', 'sdd1']

角色/ LVM /任務/ main.yml

- name: Create LVM VG(s)
  lvg:
    vg: "{{ item.vg_name }}"
    pvs: "{% for disk in item.vg_pvs %}/dev/{{ disk }}{% if not loop.last %},{% endif %}{% endfor %}"
    state: present
  when:
    - item.vg_name not in ansible_lvm.vgs
    - "{% for disk in item.vg_pvs %}ansible_devices[{{ disk | truncate(-1) }}]['partitions']{{ disk }} is defined{% endfor %}"
  with_items: "{{ lvm_vgs }}"

為此,我添加了條件"{% for disk in item.vg_pvs %}ansible_devices[{{ disk | truncate(-1) }}]['partitions']{{ disk }} is defined{% endfor %}"但它不起作用,我總是收到以下錯誤:

任務[lvm:創建LVM VG] ******************************************* ***********
致命:[主機名]:失敗! => {“失敗”:true,“ msg”:“條件檢查'{%用於item.vg_pvs%} ansible_devices [{{disk | truncate(-1)}}]] [[partitions]] {{磁盤中的磁盤}}被定義{%endfor%}'失敗。錯誤是:意外'。'\\ n第1行\\ n \\ n錯誤似乎出在'/etc/ansible/roles/lvm/tasks/main.yml'中:第80行第3列,但可能會\\ n根據確切的語法問題而在文件的其他位置。\\ n \\ n出現問題的行似乎是:\\ n \\ n \\ n-名稱:創建LVM VG \\ n ^這里\\ n“}

如何驗證PV(分區)存在?

Ansible假設的說法when是裸Jinja2的表達式(它隱式添加{{ }}括號左右),所以你不能用一個聲明{% ... %}內。

一種解決方法是在任務中定義一個變量,並將變量名稱用作條件:

- name: Create LVM VG(s)
  lvg:
    vg: "{{ item.vg_name }}"
    pvs: "{% for disk in item.vg_pvs %}/dev/{{ disk }}{% if not loop.last %},{% endif %}{% endfor %}"
    state: present
  when:
    - item.vg_name not in ansible_lvm.vgs
    - partition_exists
  with_items: "{{ lvm_vgs }}"
  vars:
    partition_exists: "{% for disk in item.vg_pvs %}ansible_devices[{{ disk | truncate(-1) }}]['partitions']{{ disk }} is defined{% endfor %}"

我無法測試您的實際狀況,因此我將其保持不變。

techraf的 答案將我帶到了解決方案。

- name: Create LVM VG(s)
  lvg:
    vg: "{{ item.vg_name }}"
    pvs: "{% for disk in item.vg_pvs %}/dev/{{ disk }}{% if not loop.last %},{% endif %}{% endfor %}"
    state: present
  when:
    - item.vg_name not in ansible_lvm.vgs
    - partition_exists.split(';')
  with_items: "{{ lvm_vgs }}"
  vars:
    partition_exists: "{% for disk in item.vg_pvs %}ansible_devices[{{ disk | truncate(-1) }}]['partitions']{{ disk }} is defined{% if not loop.last %};{% endif %}{% endfor %}"
  tags: ['storage', 'lvm']

由於item.vg_pvs可能包含多個元素,因此需要將變量partition_exists創建為列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM