天天看点

Ansible Conditionals

 一、条件语句

    条件判断语句,就是根据某些变量的值来控制Ansible的执行流程。控制某些主机执行某些操作与不执行某些操作。根据某些操作结果,判断是否执行其它操作等等。

    Ansible的条件判断语句只有 when 语句,结合变量使用才能显示出它的价值。when的用法:在想要进行判断的语句下面添加when语句即可进行条件判断.

二、示例

支持判断的操作符

1、比较操作符

       ==       !=       >       >=       <       <=

2、逻辑运算符

       and       or       not

tasks:                #简单的判断
   - name: "shutdown Debian flavored systems"
     command: /sbin/shutdown -t now
     when: ansible_os_family == "Debian"      
tasks:                 #组合形式的判断
  - name: "shutdown CentOS 6 and Debian 7 systems"
    command: /sbin/shutdown -t now    
    when: (ansible_distribution == "CentOS" and ansible_distribution_major_version == "6") or
          (ansible_distribution == "Debian" and ansible_distribution_major_version == "7")      
tasks:                   #基于某些task的结果,执行相应的task
  - command: /bin/false
    register: result   
    ignore_errors: True
  - command: /bin/something
    when: result|failed
  - command: /bin/something_else
    when: result|success
  - command: /bin/still/something_else
    when: result|skipped      
tasks:                      #如果一些变量没有定义,可以使用Jinja2的define测试。,来执行一些操作
    - shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
      when: foo is defined      
 
    - fail: msg="Bailing out. this play requires 'bar'"
      when: bar is undefined      
tasks:               #有时一些变量的返回结果是字符串,但是你想对它做一些数学运算
  - shell: echo "only on Red Hat 6, derivatives, and later"
    when: ansible_os_family == "RedHat" and ansible_lsb.major_release|int >= 6      
---              #对是否执行一些外部任务进行条件判断
- hosts: local
  vars:
   test: true
 
  tasks:
  - name: Test test
    debug: msg="Hello When"
    when: test
 
  - include: pre.yml         #根据条件判断,是否include某个外部任务文件。
    when: test           
 
  roles:
    - { role: /home/aheahe/roles/test, when: test }   #结合条件判断,是否加载某个Role      
上一篇: Ansible入门
下一篇: ansible安装

继续阅读