当Ansible在处理任务时遇到错误,它会引发一个异常来中断任务的执行。可以使用failed_when
关键字来定义在何种情况下引发错误。
以下是一个示例,演示了如何使用failed_when
来引发错误:
- name: 检查文件是否存在
hosts: localhost
tasks:
- name: 检查文件
stat:
path: /path/to/file
register: file_info
failed_when: file_info.stat.exists == false
- name: 复制文件
copy:
src: /path/to/source/file
dest: /path/to/destination/file
when: file_info.stat.exists == true
在上面的示例中,首先使用stat
模块检查指定路径是否存在文件。然后,使用register
关键字将结果保存到file_info
变量中。接下来,使用failed_when
关键字来定义条件,如果文件不存在,则引发错误。
在下一个任务中,使用copy
模块复制文件。然而,在copy
任务之前,添加了一个条件when
,只有当file_info.stat.exists
为true
时,才会执行该任务。
通过这种方式,当文件不存在时,Ansible会引发错误并中断任务的执行。