# when语句
这个when应该不能算是一个[模块](http://docs.ansible.com/ansible/latest/playbooks_conditionals.html#the-when-statement)
Ansible提供when语句,可以控制任务的执行流程。
一个很简单的when语句的例子
```
tasks:
- name: "shutdown Debian flavored systems"
command: /sbin/shutdown -t now
when: ansible_os_family == "Debian
```
在符合语句中也可以使用小括号:
```
tasks:
- name: "shutdown CentOS 6 and 7 systems"
command: /sbin/shutdown -t now
when: ansible_distribution == "CentOS" and
(ansible_distribution_major_version == "6" or ansible_distribution_major_version == "7")
```
在`when`语句中也可以使用过滤器。如,我们想跳过一个语句执行中的错误,但是后续的任务的执行需要由该任务是否成功执行决定:
```
tasks:
- command: /bin/false
register: result
ignore_errors: True
- command: /bin/something
when: result|failed
- command: /bin/something_else
when: result|success
- command: /bin/still/something_else
when: result|skipped
```
有时候需要将一个字符串的变量转换为整数来进行数字比较:
```
tasks:
- shell: echo "only on Red Hat 6, derivatives, and later"
when: ansible_os_family == "RedHat" and ansible_lsb.major_release|int >= 6
```
在playbooks和inventory中定义的变量都可以使用,如,需要根据一个变量的bool值决定是否执行该任务:
```
vars:
epic: true
```
条件语句:
```
tasks:
- shell: echo "This certainly is epic!"
when: epic
```
```
tasks:
- shell: echo "This certainly isn't epic!"
when: not epic
```
如果引用的变量没有被定义,使用Jinja2的`defined`测试,可以跳过或者是抛出错误:
```
tasks:
- shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
when: foo is defined
- fail: msg="Bailing out. this play requires 'bar'"
when: bar is not defined
```
- 目录
- ansible基础
- ansible简介
- ansible安装和测试
- ansible配置文件
- yaml在ansible中的用法
- inventory
- 变量与facts
- when语句
- handler模块
- 大杂烩
- ansible模块
- copy模块
- cron模块
- debug模块
- django_manage模块
- file模块
- git模块
- hostname模块
- lineinfile模块
- mysql_user模块
- mysql_db模块
- pip模块
- selinux
- setup模块
- shell 和 command模块
- stat模块
- supervisorctl
- systemd
- timezone
- unarchive模块
- user模块
- wait_for
- yum和service模块
- 其他模块或者方法
- 其他
- 报错处理
- playbooks
- 复杂的playbook
- 循环
- roles