在Ansible中,可以使用when
关键字来实现基于条件的执行。以下是一个示例:
- name: Check if file exists
stat:
path: /path/to/file
register: file_exists
- name: Run command only if file exists
command: some_command
when: file_exists.stat.exists
在上面的示例中,首先使用stat
模块检查文件是否存在,并将结果存储在file_exists
变量中。然后,在下一个任务中,使用command
模块只有当文件存在时才执行。
除了检查文件是否存在外,when
关键字还可以用于检查变量的值、比较值等情况。例如:
- name: Check if variable is defined
command: some_command
when: my_variable is defined
- name: Check if variable is empty
command: some_command
when: my_variable | length > 0
- name: Compare variable with a value
command: some_command
when: my_variable == 'some_value'
在上面的示例中,when
关键字分别用于检查变量是否已定义、变量是否为空以及变量是否等于某个值。根据条件的结果,决定是否执行任务。