已归录
在 when 条件中对于变量而言不需要加 {{ }}
在 when 中可以使用 ==, <, <=, >, >=, !=, [not] yyy, xxx is [not] defined, mmm in nnn.
yyy 表示布尔变量 true, 1、True、yes 都等价于 true。
not yyy 表示布尔变量 false, 0、False、no 都等价于 false。
mmm in nnn 表示一个某个元素在集合中。
示例1:比较表达式的使用
---
- name: install httpd if not installed
hosts: web
tasks:
- name: check the httpd if installed
shell: rpm -qa | grep httpd
register: cfop
ignore_errors: yes
- name: install httpd if not installed
yum:
name: httpd
state: installed
when: cfop.rc != 0
示例2:布尔变量的使用
---
- name: install httpd if not installed
hosts: web
vars:
run_my_task: true
tasks:
- name: install httpd if not installed
yum:
name: httpd
state: installed
when: run_my_task
示例3:以是否定义为条件
# cat demo.yml
---
- name: install httpd if not installed
hosts: web
vars:
my_service: httpd
tasks:
- name: install {{ my_service }} if not installed
yum:
name: "{{ my_service }}"
state: installed
when: my_service is defined
示例4:集合运算
# cat demo.yml
---
- name: install httpd if not installed
hosts: web
vars:
supported_distros:
- RedHat
- Fedora
tasks:
- name: install httpd using yum
yum:
name: httpd
state: installed
when: ansible_facts['distribution'] in supported_distros
我们还可以将多个条件用逻辑 and 与 or 结合起来:
# cat demo.yml
---
- name: install httpd if not installed
hosts: web
tasks:
- name: install httpd using yum
yum:
name: httpd
state: installed
when: ansible_facts['distribution'] == "RedHat" or ansible_facts['distribution'] == "Fedora"
#when: ansible_facts['distribution'] == "RedHat" and distribution_major_version == "8"
如果条件很复杂,可以使用 > 将一行写成多行:
when: >
(ansible_facts['distribution'] == "RedHat" and
ansible_facts['distribution_major_version'] == "8")
or
(ansible_facts['distribution'] == "RedHat" and
ansible_facts['distribution_major_version'] == "28")
当以列表方式列出条件时,表示 and 运算:
when:
- ansible_facts['distribution'] == "RedHat"
- ansible_facts['distribution_major_version'] == "8"
条件表达式与 loop 结合使用:
---
- name: install mariadb if enough space on root
hosts: web
tasks:
- name: install mariadb using yum
yum:
name: mariadb-server
state: installed
loop: "{{ ansible_facts['mounts'] }}"
when: item.mount == "/" and item.size_available > 5000000000
When you use when with loop for a task, the when statement is checked for each item.