playbook的逻辑控制语句
when
loop
block
将几个任务组成一个代码块,便于针对一组操作的异常进行处理
loop循环
标准loop使用的是类似数组的方式 嵌套loop使用的是类似列表套字典的方式 散列loop可以直接使用字典形式,但是要遵循yaml的格式
loop的标准循环
loop
循环可以使用with_items
关键字或者loop
关键字重复的任务可以用以下的方式简写
- hosts : webservers
tasks :
- name : ensure some services at the latest version
yum :
name : { { item} }
state : latest
with_items :
- httpd
- php
- php- mysql
loop循环会将with_items
后面的列表中的元素依次赋值给item
变量,然后执行后面的任务 如果在变量中已经定义了一组列表变量,也可以用{{变量名称}}
的方式引用,如下:
- hosts : webservers
vars :
packages :
- httpd
- php
- php- mysql
tasks :
- name : ensure some services at the latest version
yum :
name : { { item} }
state : latest
with_items : "{{packages}}"
with_items`的引用不止限于字符串列表,还可以是类似python中的字典列表,是一对键值对,如下:
- hosts : webservers
tasks :
- name : ensure some services at the latest version
yum :
name : "{{item.key}}"
state : "{{item.value}}"
with_dict :
- [ key : 'httpd' , value : 'latest' ]
- [ key : 'php' , value : 'latest' ]
- [ key : 'php-mysql' , value : 'latest' ]
注意:如果使用when条件判断和with_items循环,when声明会对每一个item都单独进行判断
loop的嵌套循环
---
- hosts : localhost
gather_facts : False
tasks :
- name : debug loops
debug : msg="name- > { { item[ 0 ] } } value- > { { item.1 } } "
with_nested :
- [ 'A' , 'B' ]
- [ 'a' , 'b' , 'c' ]
loop的散列循环
---
- hosts : all
gather_facts : Fasle
vars :
user :
kebi :
name : zhangrongkai
addr : luotian
maoxian :
name : songlixing
addr : xiaochang
tasks :
- name : debug loops
debug : msg="name--- > { { item.key } } value--- > { { item.value.name } } addr--- { { item.value.addr } } "
with_dict : "{{ user }}"
文件配置loop
针对文件的操作可以使用with_fileglob
关键字来实现,如下:
---
- hosts : all
tasks :
- name : debug loops
debug : msg="filename--- > { { item } } "
with_fileglob :
- /tmp/*.py
实际上是调用了python中的glob
模块来实现的:glob.glob("/tmp/*.py")
随机选择loop
针对随机选择的操作可以使用with_random_choice
关键字来实现,如下:
---
- hosts : all
tasks :
- name : debug loops
debug : msg="name--- > { { item } } "
with_random_choice :
- "test1"
- "test2"
- "test3"
实际上是调用了python中的random
模块来实现的:random.choice(["test1","test2","test3"])
文件优先匹配loop
使用with_first_found
关键字可以实现文件优先匹配的操作,如下:
---
- hosts : all
tasks :
- name : debug loops
debug : msg="file--- > { { item } } "
with_first_found :
- "{{ ansible_distribution }}.yaml"
- "default.yaml
在loop循环中使用变量获取结果
在loop循环中使用变量获取结果可以使用register
关键字来实现,如下:
---
- hosts : all
tasks :
- name : debug loops
shell : "{{ item }}"
with_items :
- hostname
- uname
register : ret
- name : display loops
debug : msg="{ % for i in ret.results %} { { i.stdout } } { % endfor %} "