community.general.file_remove module – Remove files matching a pattern from a directory
Note
This module is part of the community.general collection (version 12.6.1).
You might already have this collection installed if you are using the ansible package. It is not included in ansible-core. To check whether it is installed, run ansible-galaxy collection list.
To install it, use: ansible-galaxy collection install community.general.
To use it in a playbook, specify: community.general.file_remove.
New in community.general 12.1.0
Synopsis
- This module removes files from a specified directory that match a given pattern. The pattern can include wildcards and regular expressions.
- By default, only files in the specified directory are removed (non-recursive). Use the
recursiveoption to search and remove files in subdirectories.
Parameters
Parameter | Comments |
|---|---|
file_type string | Type of files to remove. Choices:
|
path path / required | Path to the directory where files should be removed. This must be an existing directory. |
pattern string / required | Pattern to match files for removal. Supports wildcards ( Use |
recursive boolean | If If Choices:
|
use_regex boolean |
Attributes
Attribute | Support | Description |
|---|---|---|
check_mode | Support: full | Can run in |
diff_mode | Support: full | Returns details on what has changed (or possibly needs changing in |
Notes
Note
- Directories are never removed by this module, only files and optionally symbolic links.
- This module will not follow symbolic links when
recursive=true. - Be careful with patterns that might match many files, especially with
recursive=true.
Examples
- name: Remove all log files from /var/log
community.general.file_remove:
path: /var/log
pattern: "*.log"
- name: Remove all temporary files recursively
community.general.file_remove:
path: /tmp/myapp
pattern: "*.tmp"
recursive: true
- name: Remove files matching a regex pattern
community.general.file_remove:
path: /data/backups
pattern: "backup_[0-9]{8}\\.tar\\.gz"
use_regex: true
- name: Remove both files and symbolic links
community.general.file_remove:
path: /opt/app/cache
pattern: "cache_*"
file_type: any
- name: Remove all files starting with 'test_' (check mode)
community.general.file_remove:
path: /home/user/tests
pattern: "test_*"
check_mode: true
Return Values
Common return values are documented here, the following are the fields unique to this module:
Key | Description |
|---|---|
files_count integer | Number of files removed. Returned: success Sample: |
path string | The directory path that was searched. Returned: success Sample: |
removed_files list / elements=string | List of files that were removed. Returned: always Sample: |
Collection links
© 2012–2018 Michael DeHaan
© 2018–2025 Red Hat, Inc.
Licensed under the GNU General Public License version 3.
https://docs.ansible.com/projects/ansible/latest/collections/community/general/file_remove_module.html