ansible playbook 定义变量中循环的几种方式
- 一、with_items
- 二、with_sequence
- 三、with_random_choice
- 四、with_fileglob
- 五、with_indexed_items
- 六、with_dict
- 七、with_together
- 八、with_nested
一、with_items
添加多个用户
- name: add several usersuser: name={{ item }} state=present groups=youyouwith_items:- test1- test2
添加多个用户,并将用户加入不同的组内
- name: add several usersuser: name={{ item.name }} state=present groups={{ item.groups }}with_items:- { name: 'test1', groups: 'xiapi' }- { name: 'test2', groups: 'youyou' }
二、with_sequence
ansible 批量添加多个用户,创建1-20个用户
打印是按照printf格式的。
%d表示打印整型的,
%2d表示把整型数据打印最低两位,
%02d表示把整型数据打印最低两位,如果不足两位,用0补齐
- name: add several usersuser: name={{ item }} state=present groups=xiapiwith_sequence: start=1 end=20 stride=1 format="youyou%02d"
三、with_random_choice
ansible 执行是随机选择一个变量执行
- hosts: abcgather_facts: Falsetasks:- debug: msg={{ item }}with_random_choice:- "youyou"- "xiapi"- "tudou"- "digua"
四、with_fileglob
with_fileglob 匹配单个目录中的文件
- hosts: abcgather_facts: Falsetasks:- file: dest=/home/loops.log state=directory- copy: src={{ item }} dest=/tmp/ owner=root mode=600with_fileglob:- /home/*.log
五、with_indexed_items
遍历列表和索引
item.0 代表索引
item.1 代表下表
- hosts: abcgather_facts: Falsetasks:- name: indexed loop demodebug: "msg='at array position {{ item.0 }} there is a value {{ item.1 }}'"with_indexed_items: [a,b,c,d,e,f,g]
六、with_dict
此方法为Python字典方式key:value 方式调用
item.key 相当于 alice,item.value.name 相当于 Alice Appleworth,item.value.telephone 相当于123-456-789
- hosts: abcgather_facts: Falsetasks:- name: Print phone recordsdebug: msg="User {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})"with_dict: {'alice':{'name':'Alice Appleworth', 'telephone':'123-456-789'},'bob':{'name':'Bob Bananarama', 'telephone':'987-654-321'} }
七、with_together
并行遍历列表,第一遍执行是:a,1
如果列表数目不匹配则用Null 补全
tasks:- debug: "msg={{ item.0 }} and {{ item.1 }}"with_together:- [ 'a', 'b', 'c', 'd','e' ]- [ 1, 2, 3, 4 ]tags:pwd
八、with_nested
嵌套循环主要实现一对多,多对多的合并
第一次结果:悟空,a,1,w1
第二次结果:悟空,a,1,w2
第三次结果:悟空,a,1,w3
第四次结果:悟空,a,2,w1
等等……
- hosts: abcgather_facts: Falsetasks:- name: debug loopsdebug: msg="name is {{ item[0] }} vaule is {{ item[1] }} num is {{ item[2] }} num is {{ item[3] }}"with_nested:- ['悟空','猪八戒','唐僧']- ['a','b','c']- ['1','2','3']- ['w1','w2','w3']