當有需要重復性執行某個任務時,可以使用迭代機制,其使用格式為將需要迭代的內容定義為item,并通過with_items語句來表明迭代的元素列表即可
~~~
---
- hosts: webserver
user: admin
become: yes
tasks:
- name: add users
user: name={{ item.name }} state=present groups={{ item.groups }}
with_items:
- { name: 'testuser01', groups: 'wheel' }
- { name: 'testuser02', groups: 'root' }
~~~
嵌套循環
~~~
- name: give users access to multiple databases
mysql_user: name={{ item[0] }} priv={{ item[1] }}.*:ALL append_privs=yes password=foo
with_nested:
- [ 'alice', 'bob' ]
- [ 'clientdb', 'employeedb', 'providerdb' ]
~~~
遍歷字典
~~~
---
- hosts: webserver
user: admin
become: yes
tasks:
- name: print phone records
debug: msg="User {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})"
with_dict: {'alice':{'name':'Alice Appleworth', 'telephone':'123-456-789'},'bob':{'name':'Bob Bananarama', 'telephone':'987-654-3210'} }
~~~
遍歷文件
~~~
---
- hosts: all
tasks:
- debug: "msg={{ item }}"
with_file:
- first_example_file
- second_example_file
~~~
遍歷目錄 (文件匹配循環)
~~~
---
- hosts: all
tasks:
- file: dest=/etc/fooapp state=directory
- copy: src={{ item }} dest=/etc/fooapp/ owner=root mode=600
with_fileglob:
- /playbooks/files/fooapp/*
~~~
重試循環until
~~~
- action: shell /usr/bin/foo
register: result
until: result.stdout.find("all systems go") != -1
retries: 5 重試此時
delay: 10 間隔時間
~~~
- 第一章:Ansible基礎入門
- 第二章:Ansible系列手冊
- 第一節:Ansible系列之主機清單
- 第二節:Ansible系列之變量
- 第三節:Ansible系列之YAML
- 第四節:Ansible系列之條件判斷
- 第五節:Ansible系列之循環
- 第六節: Ansible系列之tags
- 第七節:Ansible系列之Jinja2
- 第三章:Ansible系列之模塊
- 第一節:user模塊
- 第二節:group模塊
- 第三節:cron模塊
- 第四節:copy模塊
- 第五節: file模塊
- 第六節:yum模塊
- 第七節:service模塊
- 第八節:shell模塊
- 第九節:script模塊
- 第十節:setup模塊
- 第十一節:filesystem和mount模塊
- 第十二節:synchronize模塊
- 第十三節: get_url模塊
- 第十四節: package模塊
- 第十五節:stat模塊
- 第十六節:unarchive模塊
- 第十七節: commang模塊
- 第四章:Ansible-playbook介紹
- 第五章:Ansible系統環境
- 第一節:Ansible Role 系統環境之epel設置