即使這個問題看起來相當簡單(并且我一直在搜索和測驗很多),我也無法弄清楚如何在單個任務中在 ansible 中回圈兩個或多個串列。
例如,一個非常簡單的例子:
我的 vars.yml :
list1:
- /tmp/dir1
- /tmp/dir2
- /tmp/dir3
list2:
- /tmp/dir4
- /tmp/dir5
- /tmp/dir6
我的任務:
task:
- name: Create basic directories if they do not exist
file:
path: "{{ DIRECTORY }}"
state: directory
loop:
- "{{ list1 }}"
- "{{ list2 }}"
loop_control:
loop_var: DIRECTORY
顯然,我可以在單個串列中的單個任務中創建所有這些,但我有很多要創建的,因此我的問題。
提前致謝,
uj5u.com熱心網友回復:
例如,給定下面的串列
list1:
- /tmp/dir1
- /tmp/dir2
- /tmp/dir3
list2:
- /tmp/dir4
- /tmp/dir5
- /tmp/dir6
list3:
- /tmp/dir1
- /tmp/dir4
- /tmp/dir9
創建這些串列的串列,然后將它們展平并僅選擇獨特的專案,例如
list3: "{{ [list1, list2, list3]|flatten|unique }}"
可能提供您正在尋找的東西
list3:
- /tmp/dir1
- /tmp/dir2
- /tmp/dir3
- /tmp/dir4
- /tmp/dir5
- /tmp/dir6
- /tmp/dir9
當然,您可以在回圈中使用它
task:
- name: Create basic directories if they do not exist
file:
path: "{{ DIRECTORY }}"
state: directory
loop: "{{ [list1, list2, list3]|flatten|unique }}"
loop_control:
loop_var: DIRECTORY
如果串列存盤在檔案中,情況會更簡單,例如
shell> cat vars.yml
list1:
- /tmp/dir1
- /tmp/dir2
- /tmp/dir3
list2:
- /tmp/dir4
- /tmp/dir5
- /tmp/dir6
list3:
- /tmp/dir1
- /tmp/dir4
- /tmp/dir9
將檔案中的變數(串列)包含到字典中
- include_vars:
file: vars.yml
name: lists
This will create the dictionary lists
lists:
list1:
- /tmp/dir1
- /tmp/dir2
- /tmp/dir3
list2:
- /tmp/dir4
- /tmp/dir5
- /tmp/dir6
list3:
- /tmp/dir1
- /tmp/dir4
- /tmp/dir9
Then, flatten the values and select unique items. The expression below creates the same list as before without explicitly knowing the lists, i.e. you can keep the code untouched and change the data in the file vars.yml only
list3: "{{ lists.values()|flatten|unique }}"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/424457.html
上一篇:Frama-C不驗證來自https://frama-c.com/html/acsl.html的歸零陣列示例
下一篇:回圈使用空欄位的打字稿物件
