条件判断语句 when
- when 的基本用法
when 是条件判断语句,类似编程语言的if
tasks:
- command: /bin/false
register: result
ignore_errors: True
- command: /bin/command
when: result |failed
- commadn: /bin/command_else
when: result|success
- command: /bin/command_else_else
when: result|skipped
- 与include一起使用
- include: tasks/sometasks.yml
when: “‘reticulating splines’ in output”
- 与role 一起使用
- host: all
roles:
- {role: debian_stock_config, when: ansible_os_family == 'debian'}
loop 循环
- 字典循环
with_items 用于迭代的list类型变量,支持简单的字符列表,哈希列表
- name: add several users
user: name{{item.name}} state=present groups={{item.groups}}
with_iterms:
- {name: 'name1', groups: 'group1'}
- {name" 'name2', groups: 'group2'}
使用 .号访问内层和外层的变量
- 循环也可以嵌套,使用[ ]访问内层和外层的循环,例如item[0]
- 对哈希表的循环
在变量文件中或者使用vars区域定义了一组列表变量items,可以这样使用
vars:
items: ["user1","user2"]
tasks:
....
with_items: "{{iterms}}"
with_dict: "{{字典名}}"
- 文件循环(with_file, with_fileglob)
with_file 是将每个文件的文件内容作为item的值
with_fileglob 是将每个文件的全路径作为item的值, 在文件目录下是非递归的, 如果是在role里面应用改循环, 默认路径是roles/role_name/files_directory
- copy: src={{ item }} dest=/etc/fooapp/ owner=root mode=600
with_fileglob:
- /playbooks/files/fooapp/*
bolck 块
- 使用block关键字可以将多个任务整合成一个块,把这个块当成一个整体,对这个块进行判断,当条件成立时,执行块中的所以语句
tasks:
- debug:
msg: "task1 not in block"
- block:
- debug:
msg: "task2 in block1"
- debug:
msg: "task3 in block1"
when: 2 > 1
- 错误处理功能
错误处理功能就是当任务出错时,执行指定的其他任务
**failed 的用法**
tasks:
- block:
- shell: 'ls /ooo'
rescue:
- debug:
msg: 'I caught an error'
**rescue的用法**
tasks:
- block:
- shell: 'ls /opt'
- shell: 'ls /testdir'
- shell: 'ls /c'
rescue:
- debug:
msg: 'I caught an error'
always:
- debug:
msg:"this always executes"
如上例所示,block中有三个任务,这三个任务中的任何一个任务错了,就会执行rescue中的任务,所以通常会使用block和rescue结合,完成“错误捕捉,报出异常”的功能
我们还可以加入always关键字,加入always以后,无论block中的任务执行成功还是失败,always中的任务总是被执行。