Last active
August 23, 2019 14:53
-
-
Save movitto/772b56a8ad5762d91f0470b4b802834b to your computer and use it in GitHub Desktop.
Take LVM snapshot / cycle old ones out at specified interval
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Take LVM snapshot / cycle old ones out at specified interval | |
# Set executable: chmod +x lvmbak.sh | |
# Make sure to setup sudo correctly: | |
# # visudo | |
# <USER> ALL= NOPASSWD: /sbin/lvcreate | |
# <USER> ALL= NOPASSWD: /sbin/lvremove | |
# <USER> ALL= NOPASSWD: /sbin/lvs | |
# Setup to run as a cronjob: | |
# (in this case daily at 11AM) | |
# $ crontab -e | |
# 0 11 * * * /home/mmorsi/lvmbak.sh | |
KEEP_PERIODS=3 # number of periods to keep snapshot | |
PERIOD_LENGTH=86400 # in seconds | |
VG="dnp00" # LVM volume group we are snapshoting | |
LV="dnv1" # Name of LVM-volume to take a snapshot of | |
BACKUP_PREFIX="dnv1-snap-" # Prefix of snapshot volume name. | |
PV="/dev/sdd" # Physical volume to create snapshot on | |
SIZE="150G" # Amount of disk space to allocate for the snapshot | |
# Create new snapshot | |
TODAY="$(date +%s)" | |
NEW_VOLUME="$BACKUP_PREFIX$TODAY" | |
if ! lvs | grep -q -F "$NEW_VOLUME"; then | |
sudo /sbin/lvcreate --size $SIZE --permission r --snapshot "$VG/$LV" --name "$NEW_VOLUME" $PV | |
else | |
echo "Backup already exists: $NEW_VOLUME" | |
fi | |
# Clean old snapshots. | |
sudo /sbin/lvs -o lv_name --noheadings | sed -n "s@$BACKUP_PREFIX@@p" | while read DATE; do | |
TS_DATE=$(date -d "@$DATE" +%s) | |
TS_NOW=$(date +%s) | |
AGE=$(( (TS_NOW - TS_DATE) / $PERIOD_LENGTH)) | |
if [ "$AGE" -ge "$KEEP_PERIODS" ]; then | |
VOLNAME="$BACKUP_PREFIX$DATE" | |
sudo /sbin/lvremove -f "$VG/$VOLNAME" | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment