IT袋

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

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

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

时间:2023-09-17 20:48:10 来源:IT袋 作者:苏晓敏
导读:Ansible的条件判断介绍和使用方式详解,# 逻辑与when: ansible_disibution == "CentOS" and ansible_disibution_major_vsion == "7"# 逻辑或when: ansible_disibution == "RedHat" or ansible_disibution == "Fedora"when: - ansible_disibution_vsi

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

# 逻辑与 when: ansible_disibution == "CentOS" and ansible_disibution_major_vsion == "7" # 逻辑或 when: ansible_disibution == "RedHat" or ansible_disibution == "Fedora" when: - ansible_disibution_vsion == "7.9" - ansible_kernel == "3.10.0-327.el7.x86_64" # 组合使用 when: => ( ansible_disibution == "RedHat" and ansible_disibution_major_vsion == "7" ) or ( ansible_disibution == "Fedora" and ansible_disibution_major_vsion == "28")

示例:

- name: uninstall and stop forewalld
  hosts: dbsrvs
  tasks:
    - name: uninstall firewalld
    yum: pkg=firwalld state=absent
    when: ansible_disibution == "CentOS" and ansible_disibution_major_vsion == "7"
    tags: uninstall_firewalld
    - name: stop and disabled iptables
    shell: systemctl stop firewalld.service && systemctl disable firewalld && systemctl stop iptables && systemctl disable iptables
    when: ansible_disibution == "CentOS" and ansible_disibution_major_vsion == "7"
    tags: stop_firewalld
###
- name: restart httpd if postfix is running
  hosts: dbsrvs
  tasks:
    - name: get postfix serv status
      command: /usr/bin/systemctl is-active postfix
      ignore_errors: yes
      register: result
      
    - name: restart apache httpd based on postfix status
      service:
        name: httpd
        state: restarted
      when: result.rc == 0

tests 配合条件判断

通过条件语句判断tpath的路径是否存在

- hosts: dbsrvs
  vars:
    tpath: /bunianSky
  tasks:
    - debug:
        msg: "file exist"
      when: tpath is exists

参数解释:

  • is exists: 用于路径存在时返回真
  • is not exists: 用于路径不存在时返回真
    • 也可以在整个条件表达式的前面使用not来取反
- hosts: dbsrvs
  vars:
    tpath: /bunianSky
  tasks:
    - debug:
        msg: "file not exist"
      when: not tpath is exists

除了 exists 方式以外,还有其他的判断方式,如下:

判断变量
  • defined:判断变量是否已定义,已定义则返回真
  • undefined:判断变量是否未定义,未定义则返回真
  • none:判断变量的值是否为空,如果变量已定义且值为空,则返回真
- hosts: dbsrvs
  gather_facts: no
  vars:
    tvar: "test"
    tvar1:
  tasks:
    - debug:
        msg: "tvar is defined"
      when: tvar is defined
    - debug:
        msg: "tvar2 is undefined"
      when: tvar2 is undefined
    - debug:
        msg: "tvar1 is none"
      when: tvar1 is none

判断执行结果

  • sucess或succeeded:通过任务执行结果返回的信息判断任务的执行状态,任务执行成功则返回true
  • failure或failed:任务执行失败则返回true
  • change或changed:任务执行状态为changed则返回true
  • skip或skipped:任务被跳过则返回true

相关阅读