Ansible find Module: Search Files and Directories (Complete Guide)
By Luca Berton · Published 2024-01-01 · Category: troubleshooting
How to use Ansible find module to search for files, directories, and links. Filter by name, age, size, regex patterns. Find and delete old files with playbook examples.
Ansible find Module: Search Files and Directories (Complete Guide)
The ansible.builtin.find module searches for files, directories, and links on remote hosts. Filter by name patterns, age, size, content, and more — then use the results in subsequent tasks.
Basic Usage
Filter by Pattern
Filter by Age
Age units: s (seconds), m (minutes), h (hours), d (days), w (weeks).
Filter by Size
Size units: b (bytes), k (KB), m (MB), g (GB).
Filter by Type
Filter by Content
Find and Delete
Find and Archive
Working with Results
Common Patterns
Cleanup Old Releases
Find Files with Wrong Permissions
FAQ
How do I find files in Ansible?
Use ansible.builtin.find with paths and patterns. Set recurse: true to search subdirectories. Register the result to use found files in subsequent tasks.
How do I find and delete old files in Ansible?
First find with an age filter (e.g., age: 30d), register the result, then loop over result.files with ansible.builtin.file: state=absent to delete them.
What is the difference between find and stat modules?
find searches for multiple files matching criteria (patterns, age, size). stat checks properties of a single known file path. Use find for discovery, stat for verification.
Can I search file contents with Ansible find?
Yes, use the contains parameter with a regex pattern: contains: 'ERROR|WARNING'. This searches file content on the remote host and returns files that match.
How do I use regex patterns with Ansible find?
Set use_regex: true and provide regex in patterns: patterns: '^access_\d{4}\.log$'. Without use_regex, patterns use glob syntax (*.log).
Conclusion
The ansible.builtin.find module is essential for file management automation — cleanup, auditing, archiving, and discovery. Combine it with file, fetch, or archive modules for complete file lifecycle management.
Related Articles • Ansible file Module: Manage Files and Directories • Ansible fetch Module: Download Files from Hosts • Ansible stat Module: Check File Properties
Category: troubleshooting