Automation guides, explanations and reader checklists on whilenetworking.com

Bash Script: Automating the Rotation of Firewall Logs on High-Throughput Edge Routers to Prevent Disk Space Exhaustion

In high-throughput network environments, edge routers generate massive volumes of log data. Without intervention, these logs can rapidly consume available…

In high-throughput network environments, edge routers generate massive volumes of log data. Without intervention, these logs can rapidly consume available storage, leading to disk exhaustion, service outages, and potential security vulnerabilities where older logs are overwritten before analysis. For IT students and junior engineers, mastering the automation of this process is a critical skill. This guide provides a practical approach to building a Bash script that automates firewall log rotation on Linux-based routers, ensuring system stability while adhering to best practices for data retention.

Understanding Log Rotation Mechanics

Before writing code, it is essential to understand how standard logging systems like rsyslog or syslog-ng handle volume. These daemons typically use a “copy-and-truncate” mechanism (e.g., copytruncate). While convenient, this method can cause race conditions where the log file is modified while an application writes to it, potentially corrupting data. A more robust approach for high-throughput scenarios involves rotating the active file to an archive and creating a fresh empty file.

The core logic of our automation script must include:
1. Size Check: Verify if the current log file exceeds a threshold (e.g., 100MB).
2. Archive Naming: Rename the current log with a timestamp or sequence number.
3. Compression: Compress the archived log to save space (using gzip).
4. Cleanup: Remove logs older than a defined retention period (e.g., 7 days).

Prerequisites and Lab Environment Setup

To safely practice this automation, you need a controlled environment. Do not run these scripts directly on production routers without rigorous testing.

Recommended Lab Setup:
* Operating System: A Linux distribution (Ubuntu, Debian, or RHEL) acting as the edge router.
* User Permissions: Scripts should be owned by root and executed with elevated privileges to access system log directories like /var/log.
* Tools Required: Standard GNU coreutils (gzip, find, ls) are pre-installed on most systems. No external dependencies are needed for this specific task.

Safety First: Always create a backup of the current log directory before deploying rotation scripts. In a lab, you can simulate high volume by generating test data:

# Simulate large log growth (Run only in a safe container or VM)
while true; do echo "$(date): INFO - Connection established from 192.168.1.$RANDOM to 10.0.0.$RANDOM" >> /var/log/firewall.log; done &

Note: Stop this simulation immediately after testing your script.

Developing the Bash Rotation Script

We will create a script named rotate_firewall_logs.sh. This script uses standard Bash constructs and avoids destructive operations by archiving first.

Step 1: Define Variables and Thresholds
Begin the script by defining configurable variables. This allows administrators to adjust retention policies without editing the core logic.

#!/bin/bash

# Configuration Variables
LOG_DIR="/var/log"
FIREWALL_LOG="$LOG_DIR/firewall.log"
ARCHIVE_DIR="$LOG_DIR/archive"
MAX_SIZE_MB=100
RETENTION_DAYS=7
COMPRESS=true

Step 2: Create Archive Directory and Handle Rotation Logic
The script must ensure the archive directory exists. If compression is enabled, it moves the file to the archive directory and compresses it in place.

# Ensure archive directory exists
mkdir -p "$ARCHIVE_DIR"

if [ -f "$FIREWALL_LOG" ]; then
    # Get current size in bytes
    CURRENT_SIZE=$(stat -c%s "$FIREWALL_LOG")

    # Convert max size to bytes (100 MB)
    MAX_BYTES=$((MAX_SIZE_MB * 1024 * 1024))

    if [ "$CURRENT_SIZE" -gt "$MAX_BYTES" ]; then
        TIMESTAMP=$(date +%Y%m%d_%H%M%S)
        ARCHIVE_FILE="$ARCHIVE_DIR/firewall.log.$TIMESTAMP"

        # Move and compress safely
        if $COMPRESS; then
            gzip -c "$FIREWALL_LOG" > "$ARCHIVE_FILE.gz"
            # Truncate the original file to zero bytes (safe for rsyslog)
            > "$FIREWALL_LOG" 
            echo "[$TIMESTAMP] Rotated: $FIREWALL_LOG -> $ARCHIVE_FILE.gz"
        else
            mv "$FIREWALL_LOG" "$ARCHIVE_FILE"
            echo "[$TIMESTAMP] Rotated (uncompressed): $FIREWALL_LOG -> $ARCHIVE_FILE"
        fi
    fi
fi

Step 3: Cleanup Old Archives
To prevent disk space exhaustion caused by old logs, the script must delete files older than the retention period. This step is crucial for long-term health.

# Delete compressed logs older than RETENTION_DAYS
find "$ARCHIVE_DIR" -name "*.gz" -type f -mtime +$RETENTION_DAYS -delete 2>/dev/null

# Optional: Delete uncompressed logs if compression is disabled
if [ $COMPRESS -eq false ]; then
    find "$ARCHIVE_DIR" -name "firewall.log.*" -type f -mtime +$RETENTION_DAYS -delete 2>/dev/null
fi

echo "Cleanup complete. Retention policy applied."

Verification and Common Error Handling

After saving the script to /usr/local/bin/rotate_firewall_logs.sh, make it executable: sudo chmod +x /usr/local/bin/rotate_firewall_logs.sh.

How to Test:
1. Manually generate a file larger than 100MB (or adjust the MAX_SIZE_MB variable temporarily for testing).
2. Run the script: sudo ./rotate_firewall_logs.sh.
3. Expected Output: You should see a success message indicating the rotation and cleanup.
4. Verification: Check that the original log file is now empty (or near empty) and an archive file exists in /var/log/archive/.

Common Errors and Fixes:
* “Permission Denied”: The script cannot write to /var/log. Fix: Ensure the script is run with sudo or owned by root.
* “No such file or directory”: The log path is incorrect. Fix: Verify the actual path of your firewall logs in /etc/rsyslog.conf or the application configuration.
* Race Condition Corruption: If the log file is actively being written to, a simple mv might truncate data mid-write. Fix: Always use gzip -c (read and write simultaneously) or rename the file then truncate, as shown in the example above.

Integrating with System Schedulers

A script only helps if it runs automatically. The most common method is using systemd timers or cron. For high-throughput routers where consistency is key, a systemd timer is preferred over cron.

Creating a Systemd Timer:
1. Create a unit file: /etc/systemd/system/firewall-log-rotate.service.
2. Create the timer file: /etc/systemd/system/firewall-log-rotate.timer.
3. Edit the timer to run every hour (or based on size checks via a wrapper).

Note: For advanced scenarios, you might write a systemd service that calls your Bash script and sends an alert via email or Slack if rotation fails. This ensures visibility into automation failures without manual checking.

Industry Application and Student Practice Task

Real-World Application

In enterprise environments, this script is often wrapped in a Python or Ansible playbook to manage fleets of routers. Ansible can push the rotation logic to hundreds of edge devices simultaneously, ensuring uniform compliance with data retention laws (e.g., GDPR) across a global infrastructure. The Bash script serves as the underlying engine for these orchestration tools.

Student Practice Task

To solidify your understanding, attempt the following task in your lab environment:
1. Modify the script to accept command-line arguments for MAX_SIZE_MB and RETENTION_DAYS.
2. Implement a logging mechanism where every rotation event is appended to /var/log/rotation_audit.log.
3. Simulate a scenario where the disk is nearly full (95% usage) and verify that your script completes successfully without crashing the system.

Conclusion

Automating firewall log rotation on high-throughput edge routers is a fundamental practice in network operations. By using Bash scripting to check file sizes, compress archives, and enforce retention policies, engineers can prevent disk exhaustion and maintain a clean, auditable security posture. This guide provided a concrete, safe, and effective method to implement these controls, moving beyond theoretical concepts to actionable code that protects critical infrastructure.

Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.