本节内容:

  • Ansible条件测试

 

一、Ansible条件测试

在ansible中还可以进行条件测试。如果需要根据变量、facts或此前任务的执行结果来做为某task执行与否的前提时要用到条件测试。

 

1. when语句

在task后添加when子句即可使用条件测试:when语句支持Jinja2表达式语法。例如:

tasks:
- name: "shutdown Debian flavored systems"
  command: /sbin/shutdown -h now
  when: ansible_os_family == "Debian"

 

when语句还可以使用Jinja2的大多“filter”,例如要忽略此前某语句额错误并基于其结果(failed或success)运行后面指定的语句,可使用类似如下形式:

tasks:
- command: /bin/false
  register: result
  ignore_errors: True
- command: /bin/sonmething
  when: result|failed
- command: /bin/something_else
  when: result|success
- command: /bin/still/something_else
  when: result|skipped

 

此外,when语句还可以使用facts或playbook中定义的变量。facts就是主机报告上来的变量。比如:

Ansible条件测试

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-02-28
  • 2022-12-23
  • 2022-12-23
  • 2021-11-09
  • 2021-04-16
  • 2021-08-18
猜你喜欢
  • 2021-10-25
  • 2021-10-03
  • 2021-11-10
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案