ansible之fail+when

fail:

   想要playbook按照我们的意愿中断任务,可以借助fail模块会终止

案列:

- hosts: test70
  remote_user: root
  tasks:
  - debug:
      msg: "1"
  - fail:
      msg: "Interrupt running playbook"
  - debug:
      msg: "2"
该案例 msg:“2”永远不会执行到

when:

   条件判断词,满足条件才会执行上面的task

案例:

- hosts: all
  remote_user: root
  tasks:
  - debug:
      msg: "System release is centos"
    when: ansible_distribution == "CentOS"
该语句会默认执行gather_facts,该debug会在获取到的信息ansible_distribution是centos才成立执行。
when里面可以使用逻辑与等 也可以分开多行写如
- 条件1 
- 条件2

fail+when:

 fail模块通常与when模块结合,如果中断剧本的条件成立,则执行fail模块,中断剧本。

案例:

- hosts: all
  remote_user: root
  tasks:
  - shell: "echo 'This is a string for testing--error'"
    register: return_value
  - fail:
      msg: "Conditions established,Interrupt running playbook"
    when: "'error' in return_value.stdout"
  - debug:
      msg: "I never execute,Because the playbook has stopped"

个人案列role里面的使用:

#不存在路径的时候fail掉
- name: check py3 is installed and force exit
  fail: msg="python3 has been installed already!" 
  when: dir_stat.stat.exists

你可能感兴趣的:(ansible之fail+when)