Ansible-playbook条件语句when的使用

when关键字

1.基本使用

当ansible_os_family是redhat的时候,执行安装vim,不是的话跳过

---
- hosts: web
  tasks:
    - name: Install VIM via yum
      yum:
        name: vim-enhanced
        state: installed
      when: ansible_os_family =="RedHat"

    - name: Install VIM via apt
      apt:
        name: vim
        state: installed
      when: ansible_os_family =="Debian"

在这里插入图片描述

在这里插入图片描述

2.比较运算符

在上面的的实例中,我们使用了"=="的比骄傲运算符,ansible中,还支持如下比较运算符

==:比较两个对象是否相等,相等则返回真。可用于比较字符串和数字
!=:比较两个对象是否不等,不等则为真。
:比较两个对象的大小,左边的值大于右边的值,则为真
<:比较两个对象的大小,左边的值小于右边的值,则为真
=:比较两个对象的大小,左边的值大于等于右边的值,则为真
<=:比较两个对象的大小,左边的值小于等于右边的值,则为真
示例

when: ansbible_machine == "x86_64"
when: max_memory <= 512

3.逻辑运算符

在Ansible中,还支持逻辑运算符

and:逻辑与,当左边和右边两个表达式同时为真,则返回真
or:逻辑或,当左右和右边两个表达式任意一个为真,则返回真
not:逻辑否,对表达式取反
():当一组表达式组合在一起,形成一个更大的表达式,组合内的所有表达式都是逻辑与的关系

示例

# 逻辑或
when: ansible_distribution == "RedHat" or ansible_distribution == "Fedora"

# 逻辑与
when: ansible_distribution_version == "7.5" and ansible_kernel == "3.10.0-327.el7.x86_64"

when:
  - ansible_distribution_version == "7.5"
  - ansible_kernel == "3.10.0-327.el7.x86_64"
#判断register注册变量的返回结果
---
- hosts: web
  tasks:
    - name: get postfix server status
      shell: systemctl is-active postfix
      register: result
    - name: print result
      debug: msg="{{result}}"
    - name: restart apache httpd based on postfix status
      service:
        name: httpd
        state: restarted
      when: result.rc == 0                     

在这里插入图片描述

4.判断变量

defined:判断变量是否已定义,已定义则返回真
undefined:判断变量是否未定义,未定义则返回真
none:判断变量的值是否为空,如果变量已定义且值为空,则返回真

- hosts: test
  gather_facts: no
  vars:
    testvar: "test"
    testvar1:
  tasks:
    - debug:
        msg: "testvar is defined"
      when: testvar is defined
    - debug:
        msg: "testvar2 is undefined"
      when: testvar2 is undefined
    - debug:
        msg: "testvar1 is none"
      when: testvar1 is none

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值