IT袋

当前位置:主页 > 经验教程 > 系统教程 >

Ansible的条件判断介绍和使用方式详解

Ansible的条件判断介绍和使用方式详解!(3)

时间:2023-09-17 20:48:10 来源:IT袋 作者:苏晓敏
导读:Ansible的条件判断介绍和使用方式详解,- hosts: dbsrvs gather_facts: no vars: doshell: true tasks: - shell: 'cat /bunianSky/allenjol' when: doshell register: result ignore_errors: true - debug: msg: "success" when: result is success - debu

Ansible的条件判断介绍和使用方式详解

- hosts: dbsrvs
  gather_facts: no
  vars:
    doshell: true
  tasks:
    - shell: 'cat /bunianSky/allenjol'
      when: doshell
      register: result
      ignore_errors: true
    - debug:
        msg: "success"
      when: result is success
      
    - debug:
        msg: "failed"
      when: result is failure
      
    - debug:
        msg: "changed"
      when: result is change
      
    - debug:
        msg: "skip"
      when: result is skip

判断路径

  • file:判断指定路径是否为一个文件,是则为真
  • directory:判断指定路径是否为一个目录,是则为真
  • link:判断指定路径是否为一个软链接,是则为真
  • mount:判断指定路径是否为一个挂载点,是则为真
  • exists:判断指定路径是否存在,存在则为真

关于路径的所有判断均是判断主控端上的路径,而非被控端上的路径

- hosts: dbsrvs
  gather_facts: no
  vars:
    tpath1: "/bunianSky/allenjol"
    tpath2: "/bunianSky"
  tasks:
    - debug:
        msg: "file"
      when: tpath1 is file
    - debug:
        msg: "directory"
      when: tpath2 is directory

判断字符串

  • lower:判断字符串中的所有字母是否都是小写,是则为真
  • upper:判断字符串中的所有字母是否都是大写,是则为真
- hosts: dbsrvs
  gather_facts: no
  vars: 
    s1: "bunian"
    s2: "BUNIAN"
  tasks:
    - debug:
        msg: "s1 is all lowercase"
      when: s1 is lower
    - debug:
        msg: "s2 is all uppercase"
      when: s2 is upper

判断整除

  • even:判断数值是否为偶数,是则为真
  • odd:判断数值是否为奇数,是则为真
  • divisibleby(n):判断是否可以整除指定的数值,是则为真
- hosts: dbsrvs
  gather_facts: no
  vars: 
    n1: 5
    n2: 10 
    n3: 20
  tasks:
    - debug: 
        msg: "n1 is an even nber"
      when: n1 is even
    - debug:
        msg: "n2 is an odd nber"
      when: n2 is odd
    - debug:
        msg: "n3 can be divided exactly by"
      when: n3 is divisibleby(3)

其他 tests 方法

  1. version:对比两个版本号的大小,或者与指定的版本号进行对比,使用语法为vsion(“版本号”,“比较操作符”)

version中使用的比较运算符说明:

  • 大于: >, gt
  • 大于等于: >=, ge
  • 小于: <, lt
  • 小于等于: <=, le
  • 等于: =, ==, eq
  • 不等于: !=, <>, ne
- hosts: dbsrvs
  vars:
    v1: 1.2
    v2: 1.3
  tasks:
    - debug:
        msg: "v1 is greater than v2"
      when: v1 is vsion(v2,">")
    - debug:
        msg: "system vsion {{ ansible_distribution_vsion }} greater than 7.3"
      when: ansible_distribution_vsion is vsion("7.3","gt")

相关阅读