话接前文,我们继续来聊聊关于循环的关键字。
“with_indexed_items”的用法,顾名思义,”with_indexed_items”应该与”索引”有关,没错,”with_indexed_items”的作用就是在循环处理列表时为列表中的每一项添加”数字索引”,”索引”从0开始,这样说可能不够直观,我们来看一个小示例,示例playbook如下:
[root@server4 ~]# vim xh14.yml
[root@server4 ~]# cat xh14.yml
---
- hosts: testB
remote_user: root
gather_facts: no
tasks:
- debug:
msg: "{{item}}"
with_indexed_items:
- test1
- test2
- test3
上例中我们定义了一个列表,列表中有3个值,test1、test2、test3,我们使用”with_indexed_items”关键字处理这个列表,然后使用debug模块输出了item的信息,那么上例playbook执行后输出的信息如下:
[root@server4 ~]# ansible-playbook xh14.yml
从上述输出信息的msg中可以看到,”with_indexed_items”在处理列表中的每一项时,按照顺序为每一项添加了编号,test1对应的索引编号是0,test2的编号是1,test3的编号是2,”with_indexed_items”将添加过编号的每一项放入到了item中,所以,我们可以在处理每一项的时候同时获取到对应的编号,playbook如下
[root@server4 ~]# vim xh14.yml
[root@server4 ~]# cat xh14.yml
---
- hosts: testB
remote_user: root
gather_facts: no
tasks:
- debug:
msg: "idnex is :{{item.0}},value is {{item.1}}"
with_indexed_items:
- test1
- test2
- test3
[root@server4 ~]# ansible-playbook xh14.yml
上例中,我们已经能够通过”with_indexed_items”获取到列表中每个项的值以及对应的编号,但是,上述两个示例都是简单的单层列表,如果遇到像前文中出现的多层嵌套列表,”with_indexed_items”会怎样处理呢?我们来试试,示例playbook如下:
[root@server4 ~]# vim xh14.yml
[root@server4 ~]# cat xh14.yml
---
- hosts: testB
remote_user: root
gather_facts: no
tasks:
- debug:
msg: "idnex is :{{item.0}},value is {{item.1}}"
with_indexed_items:
- [ test1, test2 ]
- [ test3, test4, test5 ]
- [ test6, test7 ]
如上例所示,我们定义了一个嵌套的列表,列表中的每一项又是一个小列表,我们使用”with_indexed_items”处理这个列表,上例执行后,输出如下
[root@server4 ~]# ansible-playbook xh14.yml
我们可以发现,当我们定义了两层的嵌套列表时,”with_indexed_items”会将嵌套的两层列表”拉平”,”拉平”后按照顺序为每一项编号,”拉平”效果跟之前总结的”with_flattened”效果类似(如果忘了怎样使用”with_flattened”请回顾前文),但是,当处理这种嵌套的多层列表时,”with_indexed_items”的拉平效果与”with_flattened”的完全一致么,我们再来实验一下,我们把上例的嵌套列表改的更加复杂一些,再多嵌套一层,”with_indexed_items”示例playbook如下
[root@server4 ~]# vim xh14.yml
[root@server4 ~]# cat xh14.yml
---
- hosts: testB
remote_user: root
gather_facts: no
tasks:
- debug:
msg: "idnex is :{{item.0}},value is {{item.1}}"
with_indexed_items:
- [ test1, test2 ]
- [ test3, [ test4, test5 ] ]
- [ test6, test7 ]
如上例所示,我们又在之前示例的基础上,多嵌套了一层列表,那么执行上例playbook,输出信息如下
”with_indexed_items”示例playbook如下:
[root@server4 ~]# vim xh14.yml
[root@server4 ~]# cat xh14.yml
---
- hosts: testB
remote_user: root
gather_facts: no
tasks:
- debug:
msg: "idnex is :{{item.0}},value is {{item.1}}"
with_flattened:
- [ test1, test2 ]
- [ test3, [ test4, test5 ] ]
- [ test6, test7 ]
[root@server4 ~]# ansible-playbook xh14.yml
我们可以看出问题所在,没错,当多加了一层嵌套以后,”with_indexed_items”并不能像”with_flattened”一样将嵌套的列表”完全拉平”,第二层列表中的项如果仍然是一个列表,”with_indexed_items”则不会拉平这个列表,而是将其当做一个整体进行编号。