当有需要重复性执行的任务时,可以使用迭代机制。其使用格式为将需要迭代的内容定义为item变量引用,并通过with_items语句指明迭代的元素列表即可。with_items的值是python list数据结构,每个task会循环读取list的值,然后后key的名称是item,list里面也支持python字典。
例子一:安装多个软件。
tasks:
- name: "Install Packages"
yum: name={{ item }} state=latest
with_items:
- httpd
- mysql-server
- php
例子二:批量创建多个用户。(with_items)
- hosts: slave
remote_user: suixiaofeng
sudo: yes
tasks:
- name: "add user"
user: name={{ item.name }} state=present groups={{ item.groups }}
with_items:
- {name: "test5", groups: "suixiaofeng"}
- {name: "test6", groups: "suixiaofeng"}
其中引用变量时前缀item变量是固定的,而item后跟的键名就是在with_items中定义的字典键名。
嵌套loops循环(with_nested:)
嵌套循环主要实现一对多,多对多的合并。
loops.yaml
- hosts: slave
gather_facts: False
tasks:
- name: debug loops
debug: msg="name is {{ item[0] }} vaule is {{ item[1] }} num is {{ item[2] }}"
with_nested:
- ['suixiaofeng']
- ['a','b','c']
- ['1','2','3']
散列loops(对哈希表进行循环):
with_dict
---
-
hosts: all
gather_facts: False
vars:
user:
Bob_hou:
name: Bob_Hou
shell: bash
Jmilk:
name: Jmilk
shell: zsh
tasks:
-
name: debug loops
debug: "msg=\"name -----> {{item.key }} value -----> {{item.value.name }} shell -----> {{ item.value.shell }}\""
with_dict: "{{ user }}"
文件匹配loops: