在Ansible中,可以使用when关键字来在条件语句后执行任务。以下是一个示例:
- name: Run task based on condition
hosts: all
tasks:
- name: Check if file exists
stat:
path: /path/to/file.txt
register: file_stat
- name: Run task if file exists
command: echo "File exists"
when: file_stat.stat.exists
- name: Run task if file does not exist
command: echo "File does not exist"
when: not file_stat.stat.exists
在上面的示例中,我们首先使用stat
模块检查文件是否存在,并将结果存储在file_stat
变量中。然后,根据文件是否存在的条件,使用when
关键字来决定是否执行特定的任务。
在第一个任务中,我们使用when: file_stat.stat.exists
来检查文件是否存在,如果存在,则执行该任务(打印"File exists")。在第二个任务中,我们使用when: not file_stat.stat.exists
来检查文件是否不存在,如果不存在,则执行该任务(打印"File does not exist")。
通过使用when
关键字和条件语句,可以在Ansible中根据特定条件来执行任务。