3-3 循环语法
最后更新于:2022-04-02 07:38:00
#### 循环语法(列表)
一次安装多个软件
```yaml
---
- hosts: all
tasks:
- name: debug loops
debug: msg="{{item}}"
with_items:
- one
- tow
- three
- four
```
#### 循环语法(字典)
```yaml
---
- hosts: all
tasks:
- name: debug dict
debug: msg="name-->{{item.key}} value-->{{item.value}}"
with_items:
- {key: "one", value: "v1"}
- {key: "two", value: "v2"}
```
#### 嵌套循环
注意关键字变化
```yaml
---
- hosts: all
tasks:
- name: debug dict
debug: msg="name->{{item[0]}} value->{{item[1]}}"
with_nested:
- ['A', 'B']
- ['a', 'b', 'c']
```
#### 散列循环(失败)
```yaml
---
- hosts: all
gather_facts: no
vars:
user:
sheng:
name: ding
shell: bash
ceshi:
name: zhang
shell: zsh
tasks:
- name: debug shell
debug: msg="{{item.key}}"
with_dict: "{{user}}"
```
#### 文件循环
```yaml
---
- hosts: all
gather_facts: false
tasks:
- name: loop file
debug: msg="{{item}}"
with_fileglob:
- /etc/ansible/playbook/*.yml
```
#### 判断语句
判断文件第一行是不是abc
```yaml
---
- hosts: all
gather_facts: no
tasks:
- name: debug loop judgement
shell: cat /tmp/abc
register: hosts
until: hosts.stdout.startswith("abc")
retries: 5
delay: 5
```
';