How to Find All Files with a specific Extension with Ansible?
I'm going to show you a live Playbook with some simple Ansible code.
I'm Luca Berton and welcome to today's episode of Ansible Pilot.
Ansible Find All Files with Extension
ansible.builtin.find
- Return a list of files based on specific criteria
Today we're talking about the Ansible module find.
The full name is ansible.builtin.find, which means that is part of the collection included in the ansible-core builtin collection.
This module returns a list of files based on specific criteria using the find popular Unix command.
Parameters
- paths string - List of paths of directories to search
- hidden boolean - no/yes
- recurse boolean - recursively descend into the directory looking for files
- file_type string - file/directory/any/link
- patterns list - search (shell or regex) pattern(s)
- use_regex boolean - no/yes - file globs (shell) / python regexes
The most important parameters of the find module for this use case.
The mandatory parameter paths specify the list of paths of directories to search.
You could include hidden files with the hidden parameter.
As well as recurse in any directory under the main path with the recurse parameter.
Another useful parameter is file_type, which defaults to file but you could filter for directory, link, or any filesystem object type.
Specify what to search under the patterns list.
Ansible by default uses file globs (shell) patterns but you could specify also python regexes enabling the use_regex parameter.
Links
- [
ansible.builtin.find](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/find_module.html)
Playbook
How to Find All Files with Extension with Ansible Playbook.
I'm going to search only the files and directories under the example folder of my login users (devops) and list all the files with the ".cnf" extension.
This code has no dangerous effect on the target machine.
code
``yaml
---
- name: find Playbook
hosts: all
vars:
mypath: "/home/devops/example"
mypattern: '*.cnf'
tasks:
- name: search files
ansible.builtin.find:
paths: "{{ mypath }}"
hidden: true
recurse: true
file_type: any
patterns: "{{ mypattern }}"
register: found_files
- name: print files
ansible.builtin.debug:
var: found_files
`
execution
``bash
$ ansible-playbook -i virtualmachines/demo/inventory file_management/file_find.yml
PLAY [find Playbook] **
TASK [Gathering Facts]
ok: [demo.example.com]
TASK [search files] *
ok: [demo.example.com]
TASK [print files]
ok: [demo.example.com] => {