| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2025, Shahar Golshani (@shahargolshani) |
| 4 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
DOCUMENTATION = r""" |
| 10 |
module: file_remove |
| 11 |
|
| 12 |
short_description: Remove files matching a pattern from a directory |
| 13 |
|
| 14 |
description: |
| 15 |
- This module removes files from a specified directory that match a given pattern. |
| 16 |
The pattern can include wildcards and regular expressions. |
| 17 |
- By default, only files in the specified directory are removed (non-recursive). |
| 18 |
Use the O(recursive) option to search and remove files in subdirectories. |
| 19 |
|
| 20 |
version_added: "12.1.0" |
| 21 |
|
| 22 |
author: |
| 23 |
- Shahar Golshani (@shahargolshani) |
| 24 |
|
| 25 |
extends_documentation_fragment: |
| 26 |
- community.general._attributes |
| 27 |
|
| 28 |
attributes: |
| 29 |
check_mode: |
| 30 |
support: full |
| 31 |
diff_mode: |
| 32 |
support: full |
| 33 |
|
| 34 |
options: |
| 35 |
path: |
| 36 |
description: |
| 37 |
- Path to the directory where files should be removed. |
| 38 |
- This must be an existing directory. |
| 39 |
type: path |
| 40 |
required: true |
| 41 |
|
| 42 |
pattern: |
| 43 |
description: |
| 44 |
- Pattern to match files for removal. |
| 45 |
- Supports wildcards (V(*), V(?), V([seq]), V([!seq])) for glob-style matching. |
| 46 |
- Use O(use_regex=true) to interpret this as a regular expression instead. |
| 47 |
type: str |
| 48 |
required: true |
| 49 |
|
| 50 |
use_regex: |
| 51 |
description: |
| 52 |
- If V(true), O(pattern) is interpreted as a regular expression. |
| 53 |
- If V(false), O(pattern) is interpreted as a glob-style wildcard pattern. |
| 54 |
type: bool |
| 55 |
default: false |
| 56 |
|
| 57 |
recursive: |
| 58 |
description: |
| 59 |
- If V(true), search for files recursively in subdirectories. |
| 60 |
- If V(false), only files in the specified directory are removed. |
| 61 |
type: bool |
| 62 |
default: false |
| 63 |
|
| 64 |
file_type: |
| 65 |
description: |
| 66 |
- Type of files to remove. |
| 67 |
type: str |
| 68 |
choices: |
| 69 |
file: remove only regular files. |
| 70 |
link: remove only symbolic links. |
| 71 |
any: remove both files and symbolic links. |
| 72 |
default: file |
| 73 |
|
| 74 |
notes: |
| 75 |
- Directories are never removed by this module, only files and optionally symbolic links. |
| 76 |
- This module will not follow symbolic links when O(recursive=true). |
| 77 |
- Be careful with patterns that might match many files, especially with O(recursive=true). |
| 78 |
""" |
| 79 |
|
| 80 |
EXAMPLES = r""" |
| 81 |
- name: Remove all log files from /var/log |
| 82 |
community.general.file_remove: |
| 83 |
path: /var/log |
| 84 |
pattern: "*.log" |
| 85 |
|
| 86 |
- name: Remove all temporary files recursively |
| 87 |
community.general.file_remove: |
| 88 |
path: /tmp/myapp |
| 89 |
pattern: "*.tmp" |
| 90 |
recursive: true |
| 91 |
|
| 92 |
- name: Remove files matching a regex pattern |
| 93 |
community.general.file_remove: |
| 94 |
path: /data/backups |
| 95 |
pattern: "backup_[0-9]{8}\\.tar\\.gz" |
| 96 |
use_regex: true |
| 97 |
|
| 98 |
- name: Remove both files and symbolic links |
| 99 |
community.general.file_remove: |
| 100 |
path: /opt/app/cache |
| 101 |
pattern: "cache_*" |
| 102 |
file_type: any |
| 103 |
|
| 104 |
- name: Remove all files starting with 'test_' (check mode) |
| 105 |
community.general.file_remove: |
| 106 |
path: /home/user/tests |
| 107 |
pattern: "test_*" |
| 108 |
check_mode: true |
| 109 |
""" |
| 110 |
|
| 111 |
RETURN = r""" |
| 112 |
removed_files: |
| 113 |
description: List of files that were removed. |
| 114 |
type: list |
| 115 |
elements: str |
| 116 |
returned: always |
| 117 |
sample: ['/var/log/app.log', '/var/log/error.log'] |
| 118 |
|
| 119 |
files_count: |
| 120 |
description: Number of files removed. |
| 121 |
type: int |
| 122 |
returned: success |
| 123 |
sample: 2 |
| 124 |
|
| 125 |
path: |
| 126 |
description: The directory path that was searched. |
| 127 |
type: str |
| 128 |
returned: success |
| 129 |
sample: /var/log |
| 130 |
""" |
| 131 |
|
| 132 |
|
| 133 |
import glob |
| 134 |
import os |
| 135 |
import re |
| 136 |
import typing as t |
| 137 |
|
| 138 |
from ansible.module_utils.basic import AnsibleModule |
| 139 |
|
| 140 |
|
| 141 |
def find_matching_files( |
| 142 |
path: str, pattern: str, use_regex: bool, recursive: bool, file_type: t.Literal["file", "link", "any"] |
| 143 |
) -> list[str]: |
| 144 |
"""Find all files matching the pattern in the given path.""" |
| 145 |
matching_files = [] |
| 146 |
|
| 147 |
if use_regex: |
| 148 |
# Use regular expression matching |
| 149 |
regex = re.compile(pattern) |
| 150 |
if recursive: |
| 151 |
for root, _dirs, files in os.walk(path, followlinks=False): |
| 152 |
for filename in files: |
| 153 |
if regex.match(filename) or regex.search(filename): |
| 154 |
full_path = os.path.join(root, filename) |
| 155 |
if should_include_file(full_path, file_type): |
| 156 |
matching_files.append(full_path) |
| 157 |
else: |
| 158 |
for filename in os.listdir(path): |
| 159 |
if regex.match(filename) or regex.search(filename): |
| 160 |
full_path = os.path.join(path, filename) |
| 161 |
if should_include_file(full_path, file_type): |
| 162 |
matching_files.append(full_path) |
| 163 |
else: |
| 164 |
# Use glob pattern matching |
| 165 |
if recursive: |
| 166 |
glob_pattern = os.path.join(path, "**", pattern) |
| 167 |
matching_files = [f for f in glob.glob(glob_pattern, recursive=True) if should_include_file(f, file_type)] |
| 168 |
else: |
| 169 |
glob_pattern = os.path.join(path, pattern) |
| 170 |
matching_files = [f for f in glob.glob(glob_pattern) if should_include_file(f, file_type)] |
| 171 |
|
| 172 |
return sorted(matching_files) |
| 173 |
|
| 174 |
|
| 175 |
def should_include_file(file_path: str, file_type: t.Literal["file", "link", "any"]) -> bool: |
| 176 |
"""Determine if a file should be included based on its type.""" |
| 177 |
# Never include directories |
| 178 |
if os.path.isdir(file_path): |
| 179 |
return False |
| 180 |
|
| 181 |
is_link = os.path.islink(file_path) |
| 182 |
is_file = os.path.isfile(file_path) |
| 183 |
|
| 184 |
if file_type == "file": |
| 185 |
return is_file and not is_link |
| 186 |
elif file_type == "link": |
| 187 |
return is_link |
| 188 |
else: |
| 189 |
return is_file or is_link |
| 190 |
|
| 191 |
|
| 192 |
def remove_files(module: AnsibleModule, files: list[str]) -> tuple[list[str], list[tuple[str, str]]]: |
| 193 |
"""Remove the specified files and return results.""" |
| 194 |
removed_files = [] |
| 195 |
failed_files = [] |
| 196 |
|
| 197 |
for file_path in files: |
| 198 |
try: |
| 199 |
if module.check_mode: |
| 200 |
# In check mode, just verify the file exists |
| 201 |
if os.path.exists(file_path): |
| 202 |
removed_files.append(file_path) |
| 203 |
else: |
| 204 |
raise FileNotFoundError() |
| 205 |
else: |
| 206 |
# Actually remove the file |
| 207 |
os.remove(file_path) |
| 208 |
removed_files.append(file_path) |
| 209 |
except FileNotFoundError: |
| 210 |
module.warn(f"File not found (likely removed by other process): {file_path}") |
| 211 |
except OSError as e: |
| 212 |
failed_files.append((file_path, str(e))) |
| 213 |
|
| 214 |
return removed_files, failed_files |
| 215 |
|
| 216 |
|
| 217 |
def main() -> None: |
| 218 |
module = AnsibleModule( |
| 219 |
argument_spec=dict( |
| 220 |
path=dict(type="path", required=True), |
| 221 |
pattern=dict(type="str", required=True), |
| 222 |
use_regex=dict(type="bool", default=False), |
| 223 |
recursive=dict(type="bool", default=False), |
| 224 |
file_type=dict(type="str", default="file", choices=["file", "link", "any"]), |
| 225 |
), |
| 226 |
supports_check_mode=True, |
| 227 |
) |
| 228 |
|
| 229 |
path: str = module.params["path"] |
| 230 |
pattern: str = module.params["pattern"] |
| 231 |
use_regex: bool = module.params["use_regex"] |
| 232 |
recursive: bool = module.params["recursive"] |
| 233 |
file_type: t.Literal["file", "link", "any"] = module.params["file_type"] |
| 234 |
|
| 235 |
# Validate that the path exists and is a directory |
| 236 |
if not os.path.exists(path): |
| 237 |
module.fail_json(msg=f"Path does not exist: {path}") |
| 238 |
|
| 239 |
if not os.path.isdir(path): |
| 240 |
module.fail_json(msg=f"Path is not a directory: {path}") |
| 241 |
|
| 242 |
# Validate regex pattern if use_regex is true |
| 243 |
if use_regex: |
| 244 |
try: |
| 245 |
re.compile(pattern) |
| 246 |
except re.error as e: |
| 247 |
module.fail_json(msg=f"Invalid regular expression pattern: {e}") |
| 248 |
|
| 249 |
# Find matching files |
| 250 |
try: |
| 251 |
matching_files = find_matching_files(path, pattern, use_regex, recursive, file_type) |
| 252 |
except OSError as e: |
| 253 |
module.fail_json(msg=str(e)) |
| 254 |
|
| 255 |
# Prepare diff information |
| 256 |
diff = dict(before=dict(files=matching_files), after=dict(files=[])) |
| 257 |
|
| 258 |
# Remove the files |
| 259 |
removed_files, failed_files = remove_files(module, matching_files) |
| 260 |
|
| 261 |
# Prepare result |
| 262 |
changed = len(removed_files) > 0 |
| 263 |
|
| 264 |
result = dict( |
| 265 |
changed=changed, |
| 266 |
removed_files=removed_files, |
| 267 |
files_count=len(removed_files), |
| 268 |
path=path, |
| 269 |
msg=f"Removed {len(removed_files)} file(s) matching pattern '{pattern}'", |
| 270 |
) |
| 271 |
|
| 272 |
# Add diff if in diff mode |
| 273 |
if module._diff: |
| 274 |
result["diff"] = diff |
| 275 |
|
| 276 |
# Report any failures |
| 277 |
if failed_files: |
| 278 |
failure_msg = "; ".join([f"{f}: {e}" for f, e in failed_files]) |
| 279 |
module.fail_json( |
| 280 |
msg=f"Failed to remove some files: {failure_msg}", |
| 281 |
removed_files=removed_files, |
| 282 |
failed_files=[f for f, e in failed_files], |
| 283 |
) |
| 284 |
|
| 285 |
module.exit_json(**result) |
| 286 |
|
| 287 |
|
| 288 |
if __name__ == "__main__": |
| 289 |
main() |