当有需要重复性执行的任务时,可以使用迭代机制。其使用格式为将需要迭代的内容定义为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}
本文详细介绍了Ansible中迭代机制的使用方法,包括如何利用with_items进行任务的批量执行,适用于需要重复执行相同任务的不同目标场景。通过实例展示了基本列表和字典结构的迭代应用,帮助读者掌握更高效的任务管理技巧。
943

被折叠的 条评论
为什么被折叠?



