为了账号安全,请及时绑定邮箱和手机立即绑定

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

 

可以看出条件判断主要就是结合变量使用。

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
JAVA开发工程师
手记
粉丝
1.1万
获赞与收藏
1544

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消