有時候,你想在一個task進行很多重複的操作,例如創建用戶、安裝包、或者重複執行一個操作直到某個希望的狀態。
Standard Loops 標準循環
爲了少打一些字,可以這樣寫重複的任務:
- name: add several users
user:
name: "{{ item }}"
state: present
groups: "wheel"
with_items:
- testuser1
- testuser2
如果有定義了yaml格式的list在變量文件中,或變量段落,可以這樣做:
with_items: "{{ somelist }}"
上面的例子,等價於:
- name: add user testuser1
user:
name: "testuser1"
state: present
groups: "wheel"
- name: add user testuser2
user:
name: "testuser2"
state: present
groups: "wheel"
所以呢,用loops更加靈活。
yum和apt模塊可以用with_item來執行較少的包管理事務。
- 注意
用with_items來迭代的時候,其值不一定是字符串,還可以是哈希(hashes):
- name: add several users
user:
name: "{{ item.name }}"
state: present
groups: "{{ item.groups }}"
with_items:
- { name: 'testuser1', groups: 'wheel' }
- { name: 'testuser2', groups: 'root' }
這樣會更加靈活。
loops其實是with_
和<lookup>
的組合,所以任何<lookup>
都可以當做源來迭代,上面的例子就是用了items這個<lookup>
Looping over Hashes從哈希列表循環
假設我定義了這樣一個變量:
---
users:
alice:
name: Alice Appleworth
telephone: 123-456-7890
bob:
name: Bob Bananarama
telephone: 987-654-3210
我現在要打印出名字和電話,可以用with_dict從哈希中取值:
tasks:
- name: Print phone records
debug:
msg: "User {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})"
with_dict: "{{ users }}"
格式化輸出,挺好用的。
Looping over Files 從文件中循環
with_file可以遍歷文件列表的內容,item將按順序設置爲每個文件的內容:
---
- hosts: all
tasks:
# emit a debug message containing the content of each file.
- debug:
msg: "{{ item }}"
with_file:
- first_example_file
- second_example_file
假如第一個文件內容爲hello,第二個文件內容爲world,那麼上面的執行結果如下:
TASK [debug msg={{ item }}] ******************************************************
ok: [localhost] => (item=hello) => {
"item": "hello",
"msg": "hello"
}
ok: [localhost] => (item=world) => {
"item": "world",
"msg": "world"
}