当有需要重复性执行的任务时,可以使用迭代机制。其使用格式为将需要迭代的内容定义为item变量引用,并通过with_items语句来指明迭代的元素列表即可。
可以看一下ansible权威指南的循环相关文档
例子:
- name: add several users
user: name={{ item }} state=present groups=wheel
with_items:
- testuser1
- testuser2
上面语句的功能等同于下面的语句:
- name: add user testuser1
user: name=testuser1 state=present groups=wheel
- name: add user testuser2
user: name=testuser2 state=present groups=wheel
事实上,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' }
迭代:重复同类task时使用
调用:item
定义循环列表:with_items
- apache
- php
- mysql-server
注意:with_items中的列表值也可以是字典,但引用时要使用item.key
- {name: apache, conf: conffiles/httpd.conf}
- {name: php, conf: conffiles/php.ini}
- {name: mysql-server, conf: conffiles/my.conf}