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.2.0).
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 |
|---|---|
Type of files to remove. Choices:
|
|
Path to the directory where files should be removed. This must be an existing directory. |
|
Pattern to match files for removal. Supports wildcards ( Use |
|
If If Choices:
|
|
Attributes
Attribute |
Support |
Description |
|---|---|---|
Support: full |
Can run in |
|
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 |
|---|---|
Number of files removed. Returned: success Sample: |
|
The directory path that was searched. Returned: success Sample: |
|
List of files that were removed. Returned: always Sample: |