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
Purpose: Ensures the script runs only inside a Docker or LXC container.
Implementation Details:
Checks for presence of
/.dockerenvfile (a common indicator of Docker).Uses
grepto scan/proc/1/cgroupfor the presence oflxcordocker.
Behavior:
If inside a container, proceeds silently.
If not, prints
"Docker only!"and exits with code 1.
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
Purpose: Clears existing logrotate configurations and writes a new configuration for logs in
/logsdir.Configuration Parameters:
missingok: Do not issue errors if logs are missing.rotate {{ LOG_ROTATE_AMOUNT }}: Number of rotated logs to keep; injected via template.size {{ LOG_ROTATE_SIZE }}: Minimum log file size to trigger rotation; injected via template.notifempty: Skip rotation if log is empty.copytruncate: Truncates the original log file after copying, allowing processes to continue writing without interruption.
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
Purpose: Sets ownership and permissions to ensure security and proper access.
Details:
Ownership set to
root:root(user ID 0, group ID 0).Directory
/etc/logrotate.dis executable and readable by all (755).Configuration file
/etc/logrotate.d/nodeis readable and writable by owner, readable by others (644).Log directory
/logsdiris executable and readable by all (755).
Scheduling Logrotate via Cron
echo "{{ LOG_ROTATE_SPEC | default('0 *') }} * * * /bin/chmod 755 /logsdir; /usr/sbin/logrotate -v /etc/logrotate.conf" > /etc/crontabs/root
Purpose: Creates a cron job entry for root user that runs logrotate on a schedule.
Configuration:
The cron schedule is templated by
{{ LOG_ROTATE_SPEC }}, defaulting to"0 *"meaning at the start of every hour.Each cron execution adjusts permissions on
/logsdirand then runslogrotatewith verbose output on/etc/logrotate.conf.
Starting Cron Daemon
echo "Starting crond"
crond -f
Purpose: Starts the cron daemon in the foreground to continuously execute scheduled tasks.
Effect: Ensures that log rotation runs regularly as per the cron schedule.
Template Variables
Variable | Description | Default Value |
|---|---|---|
| Number of rotated log files to keep | (must be provided) |
| Minimum log file size to trigger rotation | (must be provided) |
| Cron schedule specification for logrotate job |
|
These variables are placeholders meant to be replaced by the deployment or configuration management system before runtime.
Interaction with Other System Components
Log Directory (
/logsdir): Target directory for log files to be rotated. This directory must exist and be writable by the processes generating logs.Logrotate Configuration (
/etc/logrotate.conf): The main logrotate config file, used by the cron job to execute rotations according to the per-application rules defined in/etc/logrotate.d/node.Cron Daemon (
crond): Runs scheduled commands, in this case, triggerslogrotateperiodically.Container Environment: The script explicitly checks for containerization before proceeding, ensuring it is not run on a host system by mistake.
Usage Example
Assuming the following template variables:
LOG_ROTATE_AMOUNT=5LOG_ROTATE_SIZE=10MLOG_ROTATE_SPEC="0 */6"(every 6 hours)
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
The script uses standard Bash idioms and utilities (
grep,rm,cat,chown,chmod,echo).Logrotate options chosen (
copytruncate) allow log rotation without needing to restart applications writing to logs.Permission settings are conservative, aligning with best practices for system security.
Cron runs in the foreground (
-f), which is typical for containerized environments to keep the process active.The script uses an explicit exit when not running inside a container, preventing mis-execution on hosts.
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.