Enrico Boldori / Wiki

« Go back ⤓ Download

Linux - Apache - Apache2 vhosts backup script.sh

#!/bin/bash
#
# ------------------------------------------------------------
# Author:      Enrico Boldori
# Description: Apache2 vhosts backup script
#
# Script function:
# This script uses tar to backup each Apache2 virtual host configuration.
#
# Backups are automatically rotated, keeping the last 8 days backups under the daily folder.
# If the current day is a Sunday, today's backup is copied under the weekly folder.
# If the current day is the first day of the month, today's backup is copied under the monthly folder.
#
# Finally, this script should be added to the crontab file (crontab -e) with the following line:
# 30 23 * * * /root/apache2_vhosts_backup.sh
# ------------------------------------------------------------

# Backup configuration
BACKUP_DIR="/backup/apache2"

BACKUP_DIR_DAILY="${BACKUP_DIR}/daily"
BACKUP_DIR_WEEKLY="${BACKUP_DIR}/weekly"
BACKUP_DIR_MONTHLY="${BACKUP_DIR}/monthly"

# Create the backup folders if they do not exist
mkdir -p "${BACKUP_DIR_DAILY}"
mkdir -p "${BACKUP_DIR_WEEKLY}"
mkdir -p "${BACKUP_DIR_MONTHLY}"

chmod 700 "${BACKUP_DIR}"
chmod 700 "${BACKUP_DIR_DAILY}"
chmod 700 "${BACKUP_DIR_WEEKLY}"
chmod 700 "${BACKUP_DIR_MONTHLY}"

# Generate a timestamp in the format YYYY-MM-DD
TODAY=$(date +\%F)

# Get the day of week (1..7, 1 is Monday) and day of month (1..31)
DAY_OF_WEEK=$(date +\%u)
DAY_OF_MONTH=$(date +\%d)

# Delete old database dumps
find "${BACKUP_DIR_DAILY}"   -type f -name "*.tar.gz" -mtime +6   -delete
find "${BACKUP_DIR_WEEKLY}"  -type f -name "*.tar.gz" -mtime +27  -delete
find "${BACKUP_DIR_MONTHLY}" -type f -name "*.tar.gz" -mtime +365 -delete

# Dump the virtual hosts configuration
CONFIGURATION_DUMP_NAME="apache2_vhosts_${TODAY}.tar.gz"
CONFIGURATION_DUMP_FILE="${BACKUP_DIR_DAILY}/${CONFIGURATION_DUMP_NAME}"

tar -czf "${CONFIGURATION_DUMP_FILE}" -C /etc/apache2/sites-available .

# Ensure that only root can read the dumped file
chmod 400 "${CONFIGURATION_DUMP_FILE}"

# If on a Sunday, copy the backup to the weekly folder
if [ ${DAY_OF_WEEK} -eq 7 ]; then cp "${CONFIGURATION_DUMP_FILE}" "${BACKUP_DIR_WEEKLY}/${CONFIGURATION_DUMP_NAME}"; fi

# If on the first day of the month, copy the backup to the monthly folder
if [ ${DAY_OF_MONTH} -eq 1 ]; then cp "${CONFIGURATION_DUMP_FILE}" "${BACKUP_DIR_MONTHLY}/${CONFIGURATION_DUMP_NAME}"; fi