add cleanup for backups
This commit is contained in:
1 parent
f53ffba649
commit
753060563f
1 file changed
+23
-3
+23
-3
@@ -1,7 +1,7 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
main() {
|
main() {
|
||||||
while getopts ":l:d:t:" opt; do
|
while getopts ":l:d:t:c:h" opt; do
|
||||||
case "${opt}" in
|
case "${opt}" in
|
||||||
l)
|
l)
|
||||||
unset VM_FILTER
|
unset VM_FILTER
|
||||||
@@ -14,6 +14,10 @@ main() {
|
|||||||
t)
|
t)
|
||||||
declare -g TARGET="$OPTARG"
|
declare -g TARGET="$OPTARG"
|
||||||
;;
|
;;
|
||||||
|
c)
|
||||||
|
declare -g run_cleanup=y
|
||||||
|
declare -g files_to_keep="${OPTARG}"
|
||||||
|
;;
|
||||||
h)
|
h)
|
||||||
usage
|
usage
|
||||||
;;
|
;;
|
||||||
@@ -43,12 +47,13 @@ list_vms() {
|
|||||||
|
|
||||||
usage() {
|
usage() {
|
||||||
cat <<EOF
|
cat <<EOF
|
||||||
Usage: ${0##*/} [-l vm[,vm...]] [-d backup_dir] [-t lxc|incus] [-h]
|
Usage: ${0##*/} [-l vm[,vm...]] [-d backup_dir] [-t lxc|incus] [-c <keep n backups>] [-h]
|
||||||
|
|
||||||
Options:
|
Options:
|
||||||
-l Comma-separated list of VMs to back up
|
-l Comma-separated list of VMs to back up
|
||||||
-d Directory where backups will be stored (default: current directory)
|
-d Directory where backups will be stored (default: current directory)
|
||||||
-t Manager type: lxc or incus (default: lxc)
|
-t Manager type: lxc or incus (default: lxc)
|
||||||
|
-c Cleanup old backups keeping a set number (default: 2)
|
||||||
-h Show this message
|
-h Show this message
|
||||||
|
|
||||||
EOF
|
EOF
|
||||||
@@ -80,7 +85,22 @@ start_backup() {
|
|||||||
[[ -d "$destination" ]] || mkdir "$destination"
|
[[ -d "$destination" ]] || mkdir "$destination"
|
||||||
[[ -f "${destination}/${backup_name}" ]] && { echo "Backup already exists"; return 2; }
|
[[ -f "${destination}/${backup_name}" ]] && { echo "Backup already exists"; return 2; }
|
||||||
|
|
||||||
lxc export "$vm" "${destination}/${backup_name}"
|
lxc export "$vm" "${destination}/${backup_name}" || { echo "Error exporting $vm"; return 1; }
|
||||||
|
|
||||||
|
[[ -n "$run_cleanup" ]] && prune_backups "$destination"
|
||||||
|
}
|
||||||
|
|
||||||
|
prune_backups() {
|
||||||
|
local backup_directory="$1"
|
||||||
|
mapfile -t backup_files < <(find "$backup_directory" -maxdepth 1 -name "*.tar.gz" -printf '%T@ %p\n' | sort -n | head -n "-${files_to_keep}" | cut -d' ' -f2-)
|
||||||
|
|
||||||
|
if [[ ${#backup_files[@]} -gt 0 ]]; then
|
||||||
|
echo "Removing ${#qcow2_files[@]} old backup files for $vm (keeping last $total_files_to_keep files)"
|
||||||
|
printf '%s\0' "${backup_files[@]}" | xargs -0 rm -fv
|
||||||
|
else
|
||||||
|
echo "No old backups to remove for $vm"
|
||||||
|
fi
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
main "$@"
|
main "$@"
|
||||||
Reference in new issue
Block a user