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 users
user: name={{ item }} state=present groups=youyou
with_items:
- test1
- test2
添加多個用戶,並將用戶加入不同的組內
- name: add several users
user: 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 users
user: name={{ item }} state=present groups=xiapi
with_sequence: start=1 end=20 stride=1 format="youyou%02d"
三、with_random_choice
ansible 執行是隨機選擇一個變量執行
- hosts: abc
gather_facts: False
tasks:
- debug: msg={{ item }}
with_random_choice:
- "youyou"
- "xiapi"
- "tudou"
- "digua"
四、with_fileglob
with_fileglob 匹配單個目錄中的文件
- hosts: abc
gather_facts: False
tasks:
- file: dest=/home/loops.log state=directory
- copy: src={{ item }} dest=/tmp/ owner=root mode=600
with_fileglob:
- /home/*.log
五、with_indexed_items
遍歷列表和索引
item.0 代表索引
item.1 代表下表
- hosts: abc
gather_facts: False
tasks:
- name: indexed loop demo
debug: "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: abc
gather_facts: False
tasks:
- name: Print phone records
debug: 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: abc
gather_facts: False
tasks:
- name: debug loops
debug: 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']