Ansible check if a file exists in when statement
In Ansible, if you have playbooks with variables that are filenames, and that should point to actual files, it’s sometimes necessary to make sure the file exists before continuing.
You can use the stat
module for that, but that is sometimes cumbersome, because it requires 2 tasks (1 to run the module and register the result and then the actual tasks with a when
clause)
A simpler way is to use a lookup plugin in your when
statement.
Note that this is particularly useful for text files (xml, yaml ini, txt, …), not so much for binary files !
File lookup
You can use the file lookup and catch the error (requires at least Ansible 2.6), to check if the file exists:
- hosts: localhost
debug:
msg: "file exists"
when:
- lookup('file', '/tmp/testfile', errors='warn')
If the file does not exists, the lookup plugin is going to print a warning message and skip the execution of the task (in this case: debug
), because the result is not true-ish.
Fileglob lookup
An alternative is to use the fileglob
lookup in the when statement.
This is not going to throw errors, it’s just going to skip if there’s no file matching the (exact) pattern.
- hosts: localhost
debug:
msg: "file exists"
when:
- lookup('fileglob', '/tmp/testfile', errors='warn')