Log Rotation and Cleanup Script Prompt
Generate a safe disk-cleanup and log-rotation script that prunes old logs and artifacts by age and size with dry-run, locking, and guardrails so it never deletes the wrong directory or fills the disk mid-run.
- Target user
- Sysadmins automating disk hygiene on servers and build agents
- Difficulty
- Intermediate
- Tools
- Claude, ChatGPT
The prompt
You are an SRE who has been paged at 3am for a full disk and has also seen a cleanup script `rm -rf` the wrong path. You are paranoid for good reasons.
I will provide:
- What to clean (log dirs, build artifacts, temp, old releases)
- Retention policy (keep N days, keep last M versions, max total size)
- Whether logrotate already exists and whether files are actively written
Design the cleanup and give me a script:
1. **Use the right tool first** — if standard `logrotate` solves it, give me a `/etc/logrotate.d/` config (rotate, compress, delaycompress, copytruncate vs create, postrotate signal) and explain copytruncate's data-loss window. Only write a custom script when logrotate cannot express the policy.
2. **Targeting safely** — never operate on a path from a variable that could be empty; guard with `: "${TARGET:?must be set}"`, refuse to run on `/`, `$HOME`, or paths shorter than N segments, and require the target to be an allow-listed prefix.
3. **Selection logic** — find candidates by age (`find -mtime`/`-newermt`) and/or by keeping the newest M and deleting the rest; handle filenames with spaces/newlines via `-print0`/`mapfile -d ''`.
4. **Dry-run by default** — print exactly what would be deleted and the bytes reclaimed; only delete when `--apply` is passed.
5. **Active-file safety** — for logs being written, prefer compress-in-place or signal the writer to reopen; never delete an open log out from under a daemon.
6. **Concurrency** — `flock` on a lock file so two cron runs don't overlap.
7. **Headroom check** — abort if free space is already critically low before doing expensive work, and report before/after disk usage.
8. **Observability** — log count and bytes freed; exit non-zero if nothing could be freed but disk is still over threshold so monitoring catches it.
Provide a Python variant when the policy needs size accounting or version parsing that Bash makes ugly.
Output: (a) logrotate config if applicable, (b) the guarded Bash script with `--dry-run`/`--apply`, (c) optional Python variant, (d) a cron/systemd-timer line to schedule it.
Bias toward: dry-run first, refuse dangerous paths, never touch open files unsafely.