1、判断的变量的一些tests
defined : 判断变量是否已经定义
undefind : 判断变量是否已经定义
none : 判断变量值是否为空
---
- hosts: test70
remote_user: root
gather_facts: no
vars:
testvar: "test"
testvar1:
tasks:
- debug:
msg: "Variable is defined"
when: testvar is defined
- debug:
msg: "Variable is undefined"
when: testvar2 is undefined
- debug:
msg: "The variable is defined, but there is no value"
when: testvar1 is none
2、判断路径的一些tests
注意: 如下tests中的判断均针对于ansible主机中的路径,与目标主机无关
file:判断路径是否是一个文件
directory:判断路径是否是一个目录
link:判断路径是否是一个链接
mount:判断路径是否是一个挂载点
exists:判断路径是否存在
---
- hosts: test70
remote_user: root
gather_facts: no
vars:
testpath1: "/testdir/test"
testpath2: "/testdir/"
testpath3: "/testdir/testsoftlink"
testpath4: "/testdir/testhardlink"
testpath5: "/boot"
tasks:
- debug:
msg: "file"
when: testpath1 is file
- debug:
msg: "directory"
when: testpath2 is directory
- debug:
msg: "link"
when: testpath3 is link
- debug:
msg: "link"
when: testpath4 is link
- debug:
msg: "mount"
when: testpath5 is mount
- debug:
msg: "exists"
when: testpath1 is exists
3、判断字符串的一些tests
lower:判断包含字母的字符串中的字母是否是纯小写
upper:判断包含字母的字符串中的字母是否是纯大写
---
- hosts: test70
remote_user: root
gather_facts: no
vars:
str1: "abc"
str2: "ABC"
tasks:
- debug:
msg: "This string is all lowercase"
when: str1 is lower
- debug:
msg: "This string is all uppercase"
when: str2 is upper
4、判断整除的一些tests
even:判断是否为偶数
even:判断是否为奇数
divisibleby(num):判断是否可以整除指定的数值num
---
- hosts: test70
remote_user: root
gather_facts: no
vars:
num1: 4
num2: 7
num3: 64
tasks:
- debug:
msg: "An even number"
when: num1 is even
- debug:
msg: "An odd number"
when: num2 is odd
- debug:
msg: "Can be divided exactly by"
when: num3 is divisibleby(8)
5、判断版本tests
version:可以用于对比两个版本号的大小,或者与指定的版本号进行对比,使用语法为version(‘版本号’,‘比较操作符’)
---
- hosts: test70
remote_user: root
vars:
ver: 7.4.1708
ver1: 7.4.1707
tasks:
- debug:
msg: "This message can be displayed when the ver is greater than ver1"
when: ver is version(ver1,">")
- debug:
msg: "system version {{ansible_distribution_version}} greater than 7.3"
when: ansible_distribution_version is version("7.3","gt")
6、判断子集tests
subset:判断一个list是不是另一个list的子集
superset:判断一个list是不是另一个list的父集
---
- hosts: test70
remote_user: root
gather_facts: no
vars:
a:
- 2
- 5
b: [1,2,3,4,5]
tasks:
- debug:
msg: "A is a subset of B"
when: a is subset(b)
- debug:
msg: "B is the parent set of A"
when: b is superset(a)
7、判断字符串、数字tests
string:判断对象是否是一个字符串
number:判断对象是否是一个数字

本文介绍了Ansible中多种判断的tests。包括针对变量、路径、字符串、整除、版本、子集等方面的判断,如判断变量是否定义、路径是否为文件、字符串大小写、能否整除指定数值等,还提及判断对象是否为字符串或数字。
964

被折叠的 条评论
为什么被折叠?



