How to Check if a File Exists in Ansible (4 Methods)
By Luca Berton · Published 2024-01-01 · Category: database-automation
How to check if a file exists in Ansible using stat module, when conditional, and find module. Complete guide with playbook examples for file existence checks.
How to Check if a File Exists in Ansible (4 Methods)
Checking whether a file exists before taking action is one of the most common patterns in Ansible. Here are four methods, from simplest to most flexible.
Method 1: stat Module (Recommended)
Method 2: stat with Multiple Properties
Method 3: find Module (Multiple Files)
Method 4: creates/removes Parameters
Some modules have built-in file existence checks:
Check if Directory Exists
Check Remote vs Local File
FAQ
What is the best way to check if a file exists in Ansible?
Use ansible.builtin.stat with register, then check result.stat.exists in a when conditional. This is the standard, idempotent approach.
Can I check if a file exists on the Ansible control node?
Yes. Add delegate_to: localhost to the stat task to check files on the control node instead of the remote host.
How do I check if a file exists and is not empty?
Use stat and check both result.stat.exists and result.stat.size > 0 in your conditional.
Related Articles • Ansible stat Module: Complete Guide • Ansible find Module: Search Files • Ansible file Module: Create and Manage Files
Category: database-automation