目录
简介
在ansible 2.5及以前的版本当中,所有的循环都是使用 with_X 风格。但是从2.6版本开始,官方开始 推荐使用 loop 关键字来代替 with_X 风格的关键字。 在playbook中使用循环,直接使用loop关键字即可。实际上就是通过loop的不同使用方法来实现对应的with_x的功能。
loop的使用方法
1. loop替代with_list
loop可以替代with_list,当处理嵌套列表时,列表不会被拉平 。
- hosts: mdb
gather_facts: no
vars:
testlist:
- a
- [b,c, [1,2]]
- d
tasks:
- name: debug groups all
debug:
msg: "{
{ item }}"
loop: "{
{ testlist }}"
2. loop替代with_flattened
将所有嵌套都拉平。
- hosts: mdb
gather_facts: no
vars:
testlist:
- a
- [b,c, [1,2]]
- d
tasks:
- name: debug groups all
debug:
msg: "{
{ item }}"
loop: "{
{ testlist | flatten }}"
3. loop替代with_items
只拉平一成嵌套。
- hosts: mdb
gather_facts: no
vars:
testlist:
- a
- [b,c, [1,2]]
- d
tasks:
- name: debug groups all
debug:
msg: "{
{ item }}"
loop: "{
{ testlist | flatten(levels=1) }}"
· levels可以为2,3,4;则表示拉平2层,3层,4层嵌套。
5. loop代替 with_dict
可使用loop配合dict2items过滤器实现with_dict功能。
- hosts: mdb
gather_facts: no
vars:
users:
xhz:
name: xiaohaizhou
iphone: 185xxx
flf:
name: fulifang
iphone: 132xxx
tasks:
- name: debug groups all
debug:
msg: "user is {
{ item['key'] }} name is {
{ item['value']['name'] }} iphone is {
{ item['value']['iphone'] }}"
loop: "{
{ users | dict2items }}"
6. loop替代with_indexed_items
通过flatten过滤器(加参数),再配合 loop_control 关键字,可以替代 with_indexed_items ,当处 理多层嵌套的列表时,只有列表中的第一层会被拉平 。
- hosts: mdb
gather_facts: no
vars:
testlist:
- a
- [b,c, [1,2]]
- d
tasks:
- name: debug groups all
debug:
msg: " {
{ index }} and {
{ item }}"
loop: "{
{ testlist | flatten(levels=1) }}"
loop_control:
index_var: index
· loop_control : 用于控制循环的行为,比如在循环时获取到元素的索引 index_var :
· loop_control 的选项,让我们指定一个变量, loop_control 会将列表元素的索引 值存放到这个指定的变量中。