logrotate.j2

Overview

logrotate.j2 is a Bash script template responsible for configuring and managing log rotation inside a containerized environment. It ensures that log files under a specified directory (/logsdir) are rotated based on defined size and rotation count parameters. Moreover, it verifies that the script runs exclusively within a Docker or LXC container environment, sets appropriate permissions for configuration files and directories, and schedules the log rotation task via crond.

The script uses templating placeholders (like {{ LOG_ROTATE_AMOUNT }}, {{ LOG_ROTATE_SIZE }}, and {{ LOG_ROTATE_SPEC }}) to inject configurable values at deployment or runtime, enabling customizable log rotation behavior.


Script Workflow and Functionality

Container Environment Verification

if [[ -f /.dockerenv ]] || grep -Eq '(lxc|docker)' /proc/1/cgroup; then
    echo -n
else
    echo "Docker only!"
    exit 1
fi

Logrotate Configuration Setup

rm /etc/logrotate.d/*
cat >/etc/logrotate.d/node <<EOF
/logsdir/*.log {
    missingok
    rotate {{ LOG_ROTATE_AMOUNT }}
    size {{ LOG_ROTATE_SIZE }}
    notifempty
    copytruncate
}
EOF

File and Directory Permissions

chown 0:0 /etc/logrotate.d
chown 0:0 /etc/logrotate.d/node

chmod 755 /etc/logrotate.d
chmod 644 /etc/logrotate.d/node

chmod 755 /logsdir

Scheduling Logrotate via Cron

echo "{{ LOG_ROTATE_SPEC | default('0 *') }} * * * /bin/chmod 755 /logsdir; /usr/sbin/logrotate -v /etc/logrotate.conf" > /etc/crontabs/root

Starting Cron Daemon

echo "Starting crond"
crond -f

Template Variables

Variable

Description

Default Value

LOG_ROTATE_AMOUNT

Number of rotated log files to keep

(must be provided)

LOG_ROTATE_SIZE

Minimum log file size to trigger rotation

(must be provided)

LOG_ROTATE_SPEC

Cron schedule specification for logrotate job

"0 *" (hourly)

These variables are placeholders meant to be replaced by the deployment or configuration management system before runtime.


Interaction with Other System Components


Usage Example

Assuming the following template variables:

The generated /etc/logrotate.d/node would be:

/logsdir/*.log {
    missingok
    rotate 5
    size 10M
    notifempty
    copytruncate
}

The cron entry would be:

0 */6 * * * /bin/chmod 755 /logsdir; /usr/sbin/logrotate -v /etc/logrotate.conf

Implementation Details


Mermaid Flowchart Diagram: Script Workflow

flowchart TD
A[Start Script]
B{Inside Docker/LXC?}
C[Exit with error "Docker only!"]
D[Clear /etc/logrotate.d/*]
E[Write /etc/logrotate.d/node config]
F[Set ownership and permissions]
G[Create cron job for logrotate]
H[Start crond in foreground]
A --> B
B -- No --> C
B -- Yes --> D
D --> E
E --> F
F --> G
G --> H

This flowchart illustrates the main decision point (container environment check) and the sequential setup steps performed by the script.