[TOC]
## 循环
#### 标准循环 with_items
```
- name: add several users
user: name={{ item }} state=present groups=wheel
with_items:
- testuser1
- testuser2
```
支持列表字符串列表的方式访问
```
- name: add several users
user: name={{ item.name }} state=present groups={{ item.groups }}
with_items:
- { name: 'testuser1', groups: 'wheel' }
- { name: 'testuser2', groups: 'root' }
```
#### 嵌套循环 with_nested
with_nested 会去依次遍历所有列表
```
- name: XXXX
shell: echo {{ item[0] }} + {{ item[1] }}
with_nested:
- [ '111', '222' ]
- [ '333', '444', '555' ]
```
这个时候 ansible 的 with_nested 遍历的`item`结果为以下:
```
item=['111', '333']
item=['111', '444']
item=['111', '555']
item=['222', '333']
item=['222', '444']
item=['222', '555']
```
所以 `item[0]` 和 `item[1]`分别为`当前item` 中的第一个值和第二个值
#### 对哈希字典进行循环 with_dict
定义一个哈希字典
```
---
users:
key_1:
value_1: XXXXX
value_2: XXXXX
key_2:
value_1: XXXXX
value_2: XXXXX
```
使用 with_dict 进行循环
```
tasks:
- name: XXXXX
debug:
msg: {{ item.key }} + {{ item.value.value_1 }} + {{ item.value.value_2 }}
with_dict: {{ users }}
```
#### 对文件夹进行匹配遍历 with_fileglob
`with_fileglob`可以`匹配`遍历单个文件夹中的文件
> with_fileblob 只会匹配指定目录下的文件,而不匹配二级文件夹
```
---
- hosts: all
tasks:
- file: dest=/pwd/dir state=directory
- copy: src={{ item }} dest=/pwd/dir
with_fileglob:
- /pwd/dir/XX**.yaml # 会匹配到符合XX*.yaml的所有文件
```
#### 生成序列并循环 with_sequence
```
with_sequence: start=0 end=10 stride=2
```
- start 起始值
- end 结束值
- stride 生成序列的步长
#### 一直循环等待某事件完成 until
```
- action: shell /usr/bin/foo
register: result
until: result.stdout.find("all systems go") != -1
retries: 5 # 重试5次
delay: 10 # 每隔10秒重试1次
```
#### 在循环中赋值变量
```
- shell: echo "{{ item }}"
with_items:
- one
- two
register: echo
```
返回如下信息:
```
{
"changed": true,
"msg": "All items completed",
"results": [
{
"changed": true,
"cmd": "echo \"one\" ",
"delta": "0:00:00.003110",
"end": "2013-12-19 12:00:05.187153",
"invocation": {
"module_args": "echo \"one\"",
"module_name": "shell"
},
"item": "one",
"rc": 0,
"start": "2013-12-19 12:00:05.184043",
"stderr": "",
"stdout": "one"
},
{
"changed": true,
"cmd": "echo \"two\" ",
"delta": "0:00:00.002920",
"end": "2013-12-19 12:00:05.245502",
"invocation": {
"module_args": "echo \"two\"",
"module_name": "shell"
},
"item": "two",
"rc": 0,
"start": "2013-12-19 12:00:05.242582",
"stderr": "",
"stdout": "two"
}
]
}
```
循环检查变量
```
- name: Fail if return code is not 0
fail:
msg: "The command ({{ item.cmd }}) did not have a 0 return code"
when: item.rc != 0
with_items: "{{echo.results}}"
```
