lookup做到循环
1
---
- hosts: testB
remote_user: root
gather_facts: no
tasks:
- debug:
msg: "index is {{item.0}}, value is {{item.1}}"
with_indexed_items: ['a','b','c']
2
---
- hosts: testB
remote_user: root
gather_facts: no
tasks:
- debug:
msg: "index is {{item.0}}, value is {{item.1}}"
loop: "{{ lookup('indexed_items',['a','b','c']) }}"
lookup做到字典展示
---
- hosts: testB
remote_user: root
gather_facts: no
vars:
users:
lily: female
alex: male
tasks:
- debug:
msg: "{{item.key}} is {{item.value}}"
with_dict: "{{ users }}"
---
- hosts: testB
remote_user: root
gather_facts: no
vars:
users:
lily: female
alex: male
tasks:
- debug:
msg: "{{item.key}} is {{item.value}}"
loop: "{{ lookup('dict',users) }}"
查找lookup插件
ansible-doc -t lookup -l
lookup查看文件内容
每个文件内容逗号隔开
---
- hosts: testB
remote_user: root
gather_facts: no
tasks:
- debug:
msg: "{{ lookup('file','/testdir/file1','/testdir/file2') }}"
每个文件内容做为列表元素值
---
- hosts: testB
remote_user: root
gather_facts: no
tasks:
- debug:
msg: "{{ lookup('file','/testdir/file1','/testdir/file2',wantlist=true) }}"
loop替代with_list
---
- hosts: testB
remote_user: root
gather_facts: no
tasks:
- debug:
msg: "{{item}}"
loop: 替换了with_list
- testdir1
- testdir2
loop+lookup替代with_dict 或过滤器
---
- hosts: testB
remote_user: root
gather_facts: no
vars:
users:
lily: female
alex: male
tasks:
- debug:
msg: "{{item.key}} is {{item.value}}"
loop: "{{ lookup('dict',users) }}"
---
- hosts: testB
remote_user: root
gather_facts: no
vars:
users:
lily: female
alex: male
tasks:
- debug:
msg: "{{item.key}} is {{item.value}}"
loop: "{{ users | dict2items }}" 2.6版本之后才有的dict2items过滤器
loop将列表全部拉平 替代with_flattened
---
- hosts: testB
remote_user: root
gather_facts: no
vars:
testlist:
- a
- [b,c,[d,e]]
- f
tasks:
- debug:
msg: "{{item}}"
loop: "{{testlist | flatten}}"
loop只拉平一层列表 替代with_items
---
- hosts: testB
remote_user: root
gather_facts: no
vars:
testlist:
- a
- [b,c,[d,e]]
- f
tasks:
- debug:
msg: "{{item}}"
loop: "{{testlist | flatten(levels=1)}}"
loop_control控制循环
pause设置循环间隔为3秒
---
- hosts: testB
remote_user: root
gather_facts: no
tasks:
- debug:
msg: "{{item}}"
loop: [1,2,3]
loop_control:
pause: 3
label表示只做什么
---
- hosts: testB
remote_user: root
gather_facts: no
vars:
users:
lily:
name: lilly
gender: female
telephones: 156-546-894
alex:
name: aliex
gender: male
telephones: 213-346-358
tasks:
- debug:
msg: "{{item.key}}"
loop: "{{users | dict2items}}"
loop_control:
label: "{{item.key}}"