Debian Codegraph @

ansible_collections/community/general/plugins/modules/logrotate.py

raw
1 #!/usr/bin/python
2 # Copyright (c) 2026 Aleksandr Gabidullin <[email protected]>
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 from __future__ import annotations
7
8 DOCUMENTATION = r"""
9 module: logrotate
10 version_added: 12.5.0
11 short_description: Manage logrotate configurations
12 description:
13 - Manage C(logrotate) configuration files and settings.
14 - Create, update, or remove C(logrotate) configurations for applications and services.
15 author: "Aleksandr Gabidullin (@a-gabidullin)"
16 requirements:
17 - logrotate >= 3.8.0
18 attributes:
19 check_mode:
20 support: full
21 diff_mode:
22 support: full
23 options:
24 name:
25 description:
26 - Name of the logrotate configuration.
27 - This creates a file in O(config_dir) with this name.
28 type: str
29 required: true
30 aliases: [config_name]
31 state:
32 description:
33 - Whether the configuration should be present or absent.
34 type: str
35 choices: [present, absent]
36 default: present
37 config_dir:
38 description:
39 - Directory where logrotate configurations are stored.
40 - Using V(~/.logrotate.d) is recommended for user-specific configurations.
41 - This directory must exist before using the module.
42 type: path
43 default: /etc/logrotate.d
44 paths:
45 description:
46 - List of log file paths or patterns to rotate.
47 - Can include wildcards (for example V(/var/log/app/*.log)).
48 - Required when creating a new configuration (O(state=present) and config file does not exist).
49 - Optional when modifying existing configuration (for example to enable/disable).
50 type: list
51 elements: path
52 rotation_period:
53 description:
54 - How often to rotate the logs.
55 - If not specified when modifying an existing configuration, the existing value is preserved.
56 - When creating a new configuration, this option is only included if specified.
57 - Choice V(hourly) was added in community.general 13.0.0.
58 type: str
59 choices: [hourly, daily, weekly, monthly, yearly]
60 rotate_count:
61 description:
62 - Number of rotated log files to keep.
63 - Set to V(0) to disable rotation (keep only current log).
64 - Set to V(-1) to keep all rotated logs (not recommended).
65 type: int
66 compress:
67 description:
68 - Compress rotated log files.
69 type: bool
70 compress_options:
71 description:
72 - Options to pass to compression program.
73 - For O(compression_method=gzip), use V(-9) for best compression, V(-1) for fastest.
74 - For O(compression_method=xz), use V(-9) for best compression.
75 type: str
76 compression_method:
77 description:
78 - Compression method to use.
79 - Requires logrotate 3.18.0 or later for V(xz) and V(zstd).
80 type: str
81 choices: [gzip, bzip2, xz, zstd, lzma, lz4]
82 delay_compress:
83 description:
84 - Postpone compression of the previous log file to the next rotation cycle.
85 - Useful for applications that keep writing to the old log file for some time.
86 type: bool
87 no_delay_compress:
88 description:
89 - Opposite of O(delay_compress). Ensure compression happens immediately.
90 - Note that in logrotate, V(no_delay_compress) is the default behavior.
91 type: bool
92 shred:
93 description:
94 - Use C(shred) to securely delete rotated log files.
95 - Uses C(shred -u) to overwrite files before deleting.
96 type: bool
97 shred_cycles:
98 description:
99 - Number of times to overwrite files when using O(shred=true).
100 - When omitted, logrotate uses C(shred)'s default.
101 type: int
102 missing_ok:
103 description:
104 - Do not issue an error if the log file is missing.
105 type: bool
106 not_if_empty:
107 description:
108 - Do not rotate the log file if it is empty.
109 - Set to V(false) to rotate even empty log files (equivalent to C(ifempty) in logrotate).
110 type: bool
111 create:
112 description:
113 - Create new log file with specified permissions after rotation.
114 - Format is V(mode owner group) (for example V(0640 root adm)).
115 - Set to V(null) or omit to use V(nocreate).
116 type: str
117 copy_truncate:
118 description:
119 - Copy the log file and then truncate it in place.
120 - Useful for applications that cannot be told to close their logfile.
121 type: bool
122 copy:
123 description:
124 - Copy the log file but do not truncate the original.
125 - Takes precedence over O(rename_copy) and O(copy_truncate).
126 type: bool
127 rename_copy:
128 description:
129 - Rename and copy the log file, leaving the original in place.
130 type: bool
131 size:
132 description:
133 - Rotate log file when it grows bigger than specified size.
134 - Format is V(number[k|M|G]) (for example V(100M), V(1G)).
135 - Overrides O(rotation_period) when set.
136 - If not specified, existing value be preserved when modifying configuration.
137 - When creating new configuration, this option be omitted if not specified.
138 type: str
139 min_size:
140 description:
141 - Rotate log file only if it has grown bigger than specified size.
142 - Format is V(number[k|M|G]) (for example V(100M), V(1G)).
143 - Used with time-based rotation to avoid rotating too small files.
144 type: str
145 max_size:
146 description:
147 - Rotate log file when it grows bigger than specified size, but at most once per O(rotation_period).
148 - Format is V(number[k|M|G]) (for example V(100M), V(1G)).
149 type: str
150 max_age:
151 description:
152 - Remove rotated logs older than specified number of days.
153 type: int
154 date_ext:
155 description:
156 - Use date as extension for rotated files (using the date format specified in O(date_format) instead of sequential
157 numbers).
158 type: bool
159 date_yesterday:
160 description:
161 - Use yesterday's date for O(date_ext) instead of today's date.
162 - Useful for rotating logs that span midnight.
163 type: bool
164 date_format:
165 description:
166 - Format for date extension.
167 - Use with O(date_ext=true).
168 - Format specifiers are V(%Y) year, V(%m) month, V(%d) day, V(%s) seconds since epoch.
169 type: str
170 shared_scripts:
171 description:
172 - Run O(pre_rotate) and O(post_rotate) scripts only once for all matching log files.
173 type: bool
174 pre_rotate:
175 description:
176 - Commands to execute before rotating the log file.
177 - Can be a single string or list of commands.
178 type: list
179 elements: str
180 post_rotate:
181 description:
182 - Commands to execute after rotating the log file.
183 - Can be a single string or list of commands.
184 type: list
185 elements: str
186 first_action:
187 description:
188 - Commands to execute once before all log files that match the wildcard pattern are rotated.
189 type: list
190 elements: str
191 last_action:
192 description:
193 - Commands to execute once after all log files that match the wildcard pattern are rotated.
194 type: list
195 elements: str
196 pre_remove:
197 description:
198 - Commands to execute before removing rotated log files.
199 type: list
200 elements: str
201 su:
202 description:
203 - Set user and group for rotated files.
204 - Format is V(user group) (for example, V(www-data adm)).
205 - Set to V("") (empty string) to remove the directive from existing configurations.
206 - Set to V(null) or omit to leave the existing value unchanged (when modifying) or not set (when creating).
207 type: str
208 old_dir:
209 description:
210 - Move rotated logs into specified directory.
211 type: path
212 create_old_dir:
213 description:
214 - Create O(old_dir) directory if it does not exist.
215 type: bool
216 no_old_dir:
217 description:
218 - Keep rotated logs in the same directory as the original log.
219 type: bool
220 extension:
221 description:
222 - Extension to use for rotated log files (including dot).
223 - Useful when O(compress=false).
224 type: str
225 mail:
226 description:
227 - Mail logs to specified address when removed.
228 - Set to V(null) or omit to not mail logs.
229 type: str
230 mail_first:
231 description:
232 - Mail just-created log file, not the about-to-expire one.
233 type: bool
234 mail_last:
235 description:
236 - Mail about-to-expire log file (default).
237 type: bool
238 include:
239 description:
240 - Include additional configuration files from specified directory.
241 type: path
242 taboo_ext:
243 description:
244 - List of extensions that logrotate should not touch.
245 - Set to V(null) or empty list to clear defaults.
246 type: list
247 elements: str
248 enabled:
249 description:
250 - Whether the configuration should be enabled.
251 - When V(false), adds V(.disabled) extension to the config file.
252 type: bool
253 start:
254 description:
255 - Base number for rotated files. Allowed values are from V(0) to V(999).
256 - For example, V(1) gives files C(.1), C(.2), and so on instead of C(.0), C(.1).
257 type: int
258 backup:
259 description:
260 - Create a backup of the existing configuration file before overwriting.
261 - The backup file is created in the same directory with a timestamp suffix.
262 type: bool
263 version_added: 12.6.0
264 default: true
265 syslog:
266 description:
267 - Send logrotate messages to syslog.
268 type: bool
269 extends_documentation_fragment:
270 - community.general._attributes
271 """
272
273 EXAMPLES = r"""
274 - name: Ensure logrotate config directory exists
275 ansible.builtin.file:
276 path: /etc/logrotate.d
277 state: directory
278 mode: '0755'
279
280 - name: Configure log rotation for Nginx
281 community.general.logrotate:
282 name: nginx
283 paths:
284 - /var/log/nginx/*.log
285 rotation_period: daily
286 rotate_count: 14
287 compress: true
288 compress_options: "-9"
289 delay_compress: true
290 missing_ok: true
291 not_if_empty: true
292 create: "0640 www-data adm"
293 shared_scripts: true
294 post_rotate:
295 - "[ -f /var/run/nginx.pid ] && kill -USR1 $(cat /var/run/nginx.pid)"
296 - "echo 'Nginx logs rotated'"
297
298 - name: Configure size-based rotation for application logs
299 community.general.logrotate:
300 name: myapp
301 paths:
302 - /var/log/myapp/app.log
303 - /var/log/myapp/debug.log
304 size: 100M
305 rotate_count: 10
306 compress: true
307 compress_options: "-1"
308 date_ext: true
309 date_yesterday: true
310 date_format: -%Y%m%d.%s
311 missing_ok: true
312 copy_truncate: true
313
314 - name: Configure log rotation with secure deletion
315 community.general.logrotate:
316 name: secure-app
317 paths:
318 - /var/log/secure-app/*.log
319 rotation_period: weekly
320 rotate_count: 4
321 shred: true
322 shred_cycles: 3
323 compress: true
324 compress_options: "-9"
325
326 - name: Configure log rotation with custom start number
327 community.general.logrotate:
328 name: custom-start
329 paths:
330 - /var/log/custom/*.log
331 rotation_period: monthly
332 rotate_count: 6
333 start: 1
334 compress: true
335
336 - name: Configure log rotation with old directory
337 community.general.logrotate:
338 name: with-old-dir
339 paths:
340 - /opt/app/logs/*.log
341 rotation_period: weekly
342 rotate_count: 4
343 old_dir: /var/log/archives
344 create_old_dir: true
345 compress: true
346 compression_method: zstd
347
348 - name: Disable logrotate configuration
349 community.general.logrotate:
350 name: old-service
351 enabled: false
352
353 - name: Remove logrotate configuration
354 community.general.logrotate:
355 name: deprecated-app
356 state: absent
357
358 - name: Complex configuration with multiple scripts
359 community.general.logrotate:
360 name: complex-app
361 paths:
362 - /var/log/complex/*.log
363 rotation_period: monthly
364 rotate_count: 6
365 compress: true
366 delay_compress: false
367 pre_rotate:
368 - "echo 'Starting rotation for complex app'"
369 - "systemctl stop complex-app"
370 post_rotate:
371 - "systemctl start complex-app"
372 - "echo 'Rotation completed'"
373 - "logger -t logrotate 'Complex app logs rotated'"
374 first_action:
375 - "echo 'First action: Starting batch rotation'"
376 last_action:
377 - "echo 'Last action: Batch rotation complete'"
378
379 - name: User-specific logrotate configuration
380 community.general.logrotate:
381 name: myuser-apps
382 config_dir: ~/.logrotate.d
383 paths:
384 - ~/app/*.log
385 - ~/.cache/*/*.log
386 rotation_period: daily
387 rotate_count: 30
388 compress: true
389 su: "{{ ansible_user_id }} users"
390
391 - name: Configuration with copy instead of move
392 community.general.logrotate:
393 name: copy-config
394 paths:
395 - /var/log/copy-app/*.log
396 rotation_period: daily
397 rotate_count: 7
398 copy: true
399
400 - name: Configuration with syslog notifications
401 community.general.logrotate:
402 name: syslog-config
403 paths:
404 - /var/log/syslog-app/*.log
405 rotation_period: daily
406 rotate_count: 14
407 syslog: true
408 compress: true
409
410 - name: Configuration without compression
411 community.general.logrotate:
412 name: nocompress-config
413 paths:
414 - /var/log/nocompress/*.log
415 rotation_period: daily
416 rotate_count: 7
417 compress: false
418
419 - name: Configuration with custom taboo extensions
420 community.general.logrotate:
421 name: taboo-config
422 paths:
423 - /var/log/taboo/*.log
424 rotation_period: daily
425 rotate_count: 7
426 taboo_ext: [".backup", ".tmp", ".temp"]
427 """
428
429 RETURN = r"""
430 config_file:
431 description: Path to the created/updated logrotate configuration file.
432 type: str
433 returned: success when O(state=present)
434 sample: /etc/logrotate.d/nginx
435 config_content:
436 description: The generated logrotate configuration content.
437 type: str
438 returned: success when O(state=present)
439 sample: |
440 /var/log/nginx/*.log {
441 daily
442 rotate 14
443 compress
444 compress_options -9
445 delay_compress
446 missing_ok
447 notifempty
448 create 0640 www-data adm
449 shared_scripts
450 post_rotate
451 [ -f /var/run/nginx.pid ] && kill -USR1 $(cat /var/run/nginx.pid)
452 echo 'Nginx logs rotated'
453 endscript
454 }
455 enabled_state:
456 description: Current enabled state of the configuration.
457 type: bool
458 returned: success
459 sample: true
460 backup_file:
461 description: Path to the backup of the original configuration file, if it was backed up.
462 type: str
463 returned: success when O(backup=true) and an existing configuration was overwritten
464 sample: /etc/logrotate.d/nginx.20250101_120000
465 """
466
467 import os
468 import re
469 import tempfile
470
471 from ansible.module_utils.basic import AnsibleModule
472
473
474 class LogrotateConfig:
475 """Logrotate configuration manager."""
476
477 def __init__(self, module: AnsibleModule, logrotate_bin: str) -> None:
478 self.module = module
479 self.params = module.params
480 self.logrotate_bin = logrotate_bin
481 self.result: dict[str, object] = {
482 "changed": False,
483 "config_file": "",
484 "config_content": "",
485 "enabled_state": True,
486 }
487
488 self.config_dir = self.params["config_dir"]
489 self.config_name = self.params["name"]
490 self.disabled_suffix = ".disabled"
491
492 def get_config_path(self, enabled: bool) -> str:
493 """Get config file path based on enabled state."""
494 base_path = os.path.join(self.config_dir, self.config_name)
495 if not enabled:
496 return base_path + self.disabled_suffix
497 return base_path
498
499 def validate_parameters(self) -> None:
500 """Validate module parameters."""
501 if self.params.get("start") is not None:
502 if self.params["start"] < 0 or self.params["start"] > 999:
503 self.module.fail_json(msg="'start' must be between 0 and 999")
504
505 su_val = self.params.get("su")
506 if su_val is not None:
507 if su_val == "":
508 pass
509 else:
510 su_parts = su_val.split()
511 if len(su_parts) != 2:
512 self.module.fail_json(msg="'su' parameter must be in format 'user group' or empty string to remove")
513
514 if self.params.get("create") is not None:
515 create_val = self.params["create"]
516 if not re.match(r"^\d{3,4}(\s+\S+\s+\S+)?\s*$", create_val):
517 self.module.fail_json(
518 msg="'create' must be in format 'mode' or 'mode user group' (for example '0640' or '0640 root adm')"
519 )
520
521 if self.params.get("shred_cycles") is not None:
522 if self.params["shred_cycles"] < 1:
523 self.module.fail_json(msg="'shred_cycles' must be a positive integer")
524 if self.params.get("shred") is False:
525 self.module.fail_json(msg="'shred_cycles' requires 'shred=true'")
526
527 for size_param in ["size", "min_size", "max_size"]:
528 if self.params.get(size_param):
529 if not re.match(r"^\d+[kMG]?$", self.params[size_param], re.I):
530 self.module.fail_json(
531 msg=f"'{size_param}' must be in format 'number[k|M|G]' (for example '100M', '1G')"
532 )
533
534 if self.params["state"] == "present":
535 existing_content = self.read_existing_config()
536 if not existing_content and not self.params.get("paths"):
537 self.module.fail_json(msg="'paths' parameter is required when creating a new configuration")
538
539 def read_existing_config(self) -> str | None:
540 """Read existing configuration file, checking both enabled and disabled versions."""
541 for suffix in ["", self.disabled_suffix]:
542 config_path = os.path.join(self.config_dir, self.config_name + suffix)
543 if os.path.exists(config_path):
544 self.result["enabled_state"] = suffix == ""
545 try:
546 with open(config_path, "r") as f:
547 return f.read()
548 except Exception as e:
549 self.module.fail_json(msg=f"Failed to read config file {config_path}: {e}")
550
551 return None
552
553 def generate_config_content(self) -> str:
554 """Generate logrotate configuration content."""
555 if not self.params.get("paths"):
556 existing_content = self.read_existing_config()
557 if existing_content:
558 lines = existing_content.strip().split("\n")
559 paths = []
560 for line in lines:
561 line = line.strip()
562 if (
563 line
564 and not line.startswith("#")
565 and not line.startswith("{")
566 and not line.startswith("}")
567 and "/" in line
568 ):
569 if not any(
570 keyword in line
571 for keyword in [
572 " ",
573 "\t",
574 "hourly",
575 "daily",
576 "weekly",
577 "monthly",
578 "yearly",
579 "rotate",
580 "compress",
581 ]
582 ):
583 paths.append(line)
584
585 if paths:
586 self.params["paths"] = paths
587 else:
588 self.params["paths"] = []
589 else:
590 self.module.fail_json(
591 msg="Cannot generate configuration: no paths specified and no existing configuration found"
592 )
593
594 lines = []
595
596 paths = self.params["paths"]
597 if isinstance(paths, str):
598 paths = [paths]
599
600 for path in paths:
601 lines.append(path)
602 lines.append("{")
603 lines.append("")
604
605 rotation_period = self.params.get("rotation_period")
606 if rotation_period is not None and not self.params.get("size") and not self.params.get("max_size"):
607 lines.append(f" {rotation_period}")
608
609 if self.params.get("size") is not None:
610 lines.append(f" size {self.params['size']}")
611 elif self.params.get("max_size") is not None:
612 lines.append(f" maxsize {self.params['max_size']}")
613
614 if self.params.get("min_size") is not None:
615 lines.append(f" minsize {self.params['min_size']}")
616
617 rotate_count = self.params.get("rotate_count")
618 if rotate_count is not None:
619 lines.append(f" rotate {rotate_count}")
620
621 start_val = self.params.get("start")
622 if start_val is not None:
623 lines.append(f" start {start_val}")
624
625 compress_val = self.params.get("compress")
626 if compress_val is not None:
627 if compress_val:
628 comp_method = self.params.get("compression_method")
629 if comp_method is not None and comp_method != "gzip":
630 lines.append(f" compresscmd /usr/bin/{comp_method}")
631 if comp_method == "zstd":
632 lines.append(f" uncompresscmd /usr/bin/{comp_method} -d")
633 elif comp_method == "lz4":
634 lines.append(f" uncompresscmd /usr/bin/{comp_method} -d")
635 else:
636 lines.append(f" uncompresscmd /usr/bin/{comp_method}un{comp_method}")
637 lines.append(f" compressext .{comp_method}")
638 lines.append(" compress")
639
640 if self.params.get("compress_options") is not None:
641 lines.append(f" compressoptions {self.params['compress_options']}")
642 else:
643 lines.append(" nocompress")
644
645 delay_compress_val = self.params.get("delay_compress")
646 if delay_compress_val is not None:
647 if delay_compress_val:
648 lines.append(" delaycompress")
649
650 no_delay_compress_val = self.params.get("no_delay_compress")
651 if no_delay_compress_val is not None:
652 if no_delay_compress_val:
653 lines.append(" nodelaycompress")
654
655 shred_val = self.params.get("shred")
656 if shred_val is not None and shred_val:
657 lines.append(" shred")
658 shred_cycles_val = self.params.get("shred_cycles")
659 if shred_cycles_val is not None:
660 lines.append(f" shredcycles {shred_cycles_val}")
661
662 missing_ok_val = self.params.get("missing_ok")
663 if missing_ok_val is not None:
664 if not missing_ok_val:
665 lines.append(" nomissingok")
666 else:
667 lines.append(" missingok")
668
669 not_if_empty_val = self.params.get("not_if_empty")
670 if not_if_empty_val is not None:
671 if not_if_empty_val:
672 lines.append(" notifempty")
673 else:
674 lines.append(" ifempty")
675
676 create_val = self.params.get("create")
677 if create_val is not None:
678 lines.append(f" create {create_val}")
679
680 copy_val = self.params.get("copy")
681 rename_copy_val = self.params.get("rename_copy")
682 copy_truncate_val = self.params.get("copy_truncate")
683
684 if copy_val is not None and copy_val:
685 lines.append(" copy")
686 elif rename_copy_val is not None and rename_copy_val:
687 lines.append(" renamecopy")
688 elif copy_truncate_val is not None and copy_truncate_val:
689 lines.append(" copytruncate")
690
691 if self.params.get("max_age") is not None:
692 lines.append(f" maxage {self.params['max_age']}")
693
694 date_ext_val = self.params.get("date_ext")
695 if date_ext_val is not None and date_ext_val:
696 lines.append(" dateext")
697 date_yesterday_val = self.params.get("date_yesterday")
698 if date_yesterday_val is not None and date_yesterday_val:
699 lines.append(" dateyesterday")
700 date_format_val = self.params.get("date_format")
701 if date_format_val is not None:
702 lines.append(f" dateformat {date_format_val}")
703
704 shared_scripts_val = self.params.get("shared_scripts")
705 if shared_scripts_val is not None and shared_scripts_val:
706 lines.append(" sharedscripts")
707
708 su_val = self.params.get("su")
709 if su_val is not None:
710 if su_val != "":
711 lines.append(f" su {su_val}")
712
713 no_old_dir_val = self.params.get("no_old_dir")
714 old_dir_val = self.params.get("old_dir")
715
716 if no_old_dir_val is not None and no_old_dir_val:
717 lines.append(" noolddir")
718 elif old_dir_val is not None:
719 lines.append(f" olddir {old_dir_val}")
720 create_old_dir_val = self.params.get("create_old_dir")
721 if create_old_dir_val is not None and create_old_dir_val:
722 lines.append(" createolddir")
723
724 if self.params.get("extension") is not None:
725 lines.append(f" extension {self.params['extension']}")
726
727 mail_val = self.params.get("mail")
728 if mail_val is not None:
729 lines.append(f" mail {mail_val}")
730 mail_first_val = self.params.get("mail_first")
731 mail_last_val = self.params.get("mail_last")
732 if mail_first_val is not None and mail_first_val:
733 lines.append(" mailfirst")
734 elif mail_last_val is not None and mail_last_val:
735 lines.append(" maillast")
736
737 if self.params.get("include") is not None:
738 lines.append(f" include {self.params['include']}")
739
740 if self.params.get("taboo_ext") is not None:
741 taboo_ext = self.params["taboo_ext"]
742 if isinstance(taboo_ext, list):
743 taboo_ext = " ".join(taboo_ext)
744 if taboo_ext.strip():
745 lines.append(f" tabooext {taboo_ext}")
746
747 syslog_val = self.params.get("syslog")
748 if syslog_val is not None and syslog_val:
749 lines.append(" syslog")
750
751 scripts = {
752 "prerotate": self.params.get("pre_rotate"),
753 "postrotate": self.params.get("post_rotate"),
754 "firstaction": self.params.get("first_action"),
755 "lastaction": self.params.get("last_action"),
756 "preremove": self.params.get("pre_remove"),
757 }
758
759 for script_name, script_content in scripts.items():
760 if script_content is not None:
761 lines.append(f" {script_name}")
762 for command in script_content:
763 for line in command.strip().split("\n"):
764 if line.strip():
765 lines.append(f" {line}")
766 lines.append(" endscript")
767 lines.append("")
768
769 lines.append("}")
770
771 return "\n".join(lines)
772
773 def apply(self) -> dict[str, object]:
774 """Apply logrotate configuration."""
775 self.validate_parameters()
776 state = self.params["state"]
777
778 if not os.path.exists(self.config_dir):
779 self.module.fail_json(
780 msg=f"Config directory '{self.config_dir}' does not exist. "
781 f"Please create it manually or ensure the correct path is specified."
782 )
783
784 if state == "absent":
785 for suffix in ["", self.disabled_suffix]:
786 config_path = os.path.join(self.config_dir, self.config_name + suffix)
787 if os.path.exists(config_path):
788 if not self.module.check_mode:
789 if self.params["backup"]:
790 self.result["backup_file"] = self.module.backup_local(config_path)
791 try:
792 os.remove(config_path)
793 except Exception as e:
794 self.module.fail_json(msg=f"Failed to remove config file '{config_path}': {e}")
795 self.result["changed"] = True
796 self.result["config_file"] = config_path
797 break
798 return self.result
799
800 existing_content = self.read_existing_config()
801 current_enabled = self.result.get("enabled_state", True)
802
803 target_enabled = self.params.get("enabled")
804 if target_enabled is None:
805 target_enabled = current_enabled
806
807 only_changing_enabled = (
808 existing_content is not None and not self.params.get("paths") and target_enabled != current_enabled
809 )
810
811 if only_changing_enabled:
812 old_path = self.get_config_path(not target_enabled)
813 new_path = self.get_config_path(target_enabled)
814
815 if not os.path.exists(old_path):
816 self.module.fail_json(msg=f"Cannot change enabled state: config file '{old_path}' not found")
817 elif os.path.exists(new_path):
818 self.module.fail_json(msg=f"Cannot change enabled state: target path '{new_path}' already exists")
819
820 self.result["changed"] = True
821 if not self.module.check_mode:
822 try:
823 self.module.atomic_move(old_path, new_path, unsafe_writes=False)
824 except Exception as e:
825 self.module.fail_json(msg=f"Failed to rename config file from '{old_path}' to '{new_path}': {e}")
826
827 self.result["config_file"] = new_path
828 self.result["enabled_state"] = target_enabled
829
830 try:
831 with open(new_path, "r") as f:
832 self.result["config_content"] = f.read()
833 except Exception:
834 self.result["config_content"] = existing_content
835
836 return self.result
837
838 new_content = self.generate_config_content()
839 self.result["config_content"] = new_content
840 self.result["config_file"] = self.get_config_path(target_enabled)
841
842 needs_update = existing_content is None or existing_content != new_content or target_enabled != current_enabled
843
844 if needs_update:
845 if not self.module.check_mode:
846 try:
847 with tempfile.NamedTemporaryFile(
848 mode="w", suffix=".tmp", prefix=self.config_name + "_", dir=self.module.tmpdir, delete=False
849 ) as tmp_file:
850 tmp_file.write(new_content)
851 tmp_path = tmp_file.name
852 self.module.add_cleanup_file(tmp_path)
853 except Exception as e:
854 self.module.fail_json(msg=f"Failed to write temp config file: {e}")
855
856 test_cmd = [self.logrotate_bin, "-d", tmp_path]
857 rc, stdout, stderr = self.module.run_command(test_cmd)
858 if rc != 0:
859 self.module.fail_json(
860 msg="logrotate configuration test failed",
861 stderr=stderr,
862 stdout=stdout,
863 config_file=str(self.result["config_file"]),
864 )
865
866 config_file_path = str(self.result["config_file"])
867 for suffix in ["", self.disabled_suffix]:
868 old_path = os.path.join(self.config_dir, self.config_name + suffix)
869 if os.path.exists(old_path):
870 if self.params["backup"]:
871 self.result["backup_file"] = self.module.backup_local(old_path)
872 if old_path != config_file_path:
873 try:
874 os.remove(old_path)
875 except Exception as e:
876 self.module.fail_json(msg=f"Failed to remove old config file '{old_path}': {e}")
877
878 try:
879 self.module.atomic_move(tmp_path, config_file_path, unsafe_writes=False)
880 os.chmod(config_file_path, 0o644)
881 except Exception as e:
882 self.module.fail_json(msg=f"Failed to move config file to {config_file_path!r}: {e}")
883
884 self.result["changed"] = needs_update
885 self.result["enabled_state"] = target_enabled
886 return self.result
887
888
889 def main() -> None:
890 """Main function."""
891 module = AnsibleModule(
892 argument_spec=dict(
893 name=dict(type="str", required=True, aliases=["config_name"]),
894 state=dict(type="str", choices=["present", "absent"], default="present"),
895 config_dir=dict(type="path", default="/etc/logrotate.d"),
896 paths=dict(type="list", elements="path"),
897 rotation_period=dict(
898 type="str",
899 choices=["hourly", "daily", "weekly", "monthly", "yearly"],
900 ),
901 rotate_count=dict(type="int"),
902 compress=dict(type="bool"),
903 compress_options=dict(type="str"),
904 compression_method=dict(
905 type="str",
906 choices=["gzip", "bzip2", "xz", "zstd", "lzma", "lz4"],
907 ),
908 delay_compress=dict(type="bool"),
909 no_delay_compress=dict(type="bool"),
910 shred=dict(type="bool"),
911 shred_cycles=dict(type="int"),
912 missing_ok=dict(type="bool"),
913 not_if_empty=dict(type="bool"),
914 create=dict(type="str"),
915 copy_truncate=dict(type="bool"),
916 copy=dict(type="bool"),
917 rename_copy=dict(type="bool"),
918 size=dict(type="str"),
919 min_size=dict(type="str"),
920 max_size=dict(type="str"),
921 max_age=dict(type="int"),
922 date_ext=dict(type="bool"),
923 date_yesterday=dict(type="bool"),
924 date_format=dict(type="str"),
925 shared_scripts=dict(type="bool"),
926 pre_rotate=dict(type="list", elements="str"),
927 post_rotate=dict(type="list", elements="str"),
928 first_action=dict(type="list", elements="str"),
929 last_action=dict(type="list", elements="str"),
930 pre_remove=dict(type="list", elements="str"),
931 su=dict(type="str"),
932 old_dir=dict(type="path"),
933 create_old_dir=dict(type="bool"),
934 no_old_dir=dict(type="bool"),
935 extension=dict(type="str"),
936 mail=dict(type="str"),
937 mail_first=dict(type="bool"),
938 mail_last=dict(type="bool"),
939 include=dict(type="path"),
940 taboo_ext=dict(type="list", elements="str"),
941 enabled=dict(type="bool"),
942 start=dict(type="int"),
943 syslog=dict(type="bool"),
944 backup=dict(type="bool", default=True),
945 ),
946 mutually_exclusive=[
947 ["delay_compress", "no_delay_compress"],
948 ["old_dir", "no_old_dir"],
949 ["size", "max_size"],
950 ["copy", "copy_truncate", "rename_copy"],
951 ],
952 required_by={
953 "shred_cycles": "shred",
954 "compression_method": "compress",
955 "compress_options": "compress",
956 },
957 supports_check_mode=True,
958 )
959
960 logrotate_bin = module.get_bin_path("logrotate", required=True)
961
962 logrotate_config = LogrotateConfig(module, logrotate_bin)
963 result = logrotate_config.apply()
964 module.exit_json(**result)
965
966
967 if __name__ == "__main__":
968 main()