Harden mysqlbackup.sh script

* mysql::backup backuprotate parameter sets the number of backups to keep,
   default is 30.

 * Use bash in mysqlbackup.sh to get exit status of mysqldump when piped to
   bzip2. Unfortunately there is no easy portable way to do that.

 * Only delete old backups when current backup finished successfully.

 * Try hard not to delete files that we didn't create (i.e. README or other
   backups).
This commit is contained in:
Oleg Malashenko 2013-04-18 16:51:50 +10:00
parent 0dfa6a4857
commit 9e2540f4fc
2 changed files with 14 additions and 4 deletions

View file

@ -7,6 +7,7 @@
# [*backuppassword*] - The password of the mysql backup user.
# [*backupdir*] - The target directory of the mysqldump.
# [*backupcompress*] - Boolean to compress backup with bzip2.
# [*backuprotate*] - Number of backups to keep. Default 30
#
# Actions:
# GRANT SELECT, RELOAD, LOCK TABLES ON *.* TO 'user'@'localhost'
@ -28,6 +29,7 @@ class mysql::backup (
$backuppassword,
$backupdir,
$backupcompress = true,
$backuprotate = 30,
$ensure = 'present'
) {

View file

@ -1,4 +1,4 @@
#!/bin/sh
#!/bin/bash
#
# MySQL Backup Script
# Dumps mysql databases to a file for another backup tool to pick up.
@ -13,11 +13,19 @@
USER=<%= @backupuser %>
PASS=<%= @backuppassword %>
DIR=<%= @backupdir %>
ROTATE=<%= [ Integer(@backuprotate) - 1, 0 ].max %>
PREFIX=mysql_backup_
##### STOP CONFIG ####################################################
PATH=/usr/bin:/usr/sbin:/bin:/sbin
find $DIR -mtime +30 -exec rm -f {} \;
mysqldump -u${USER} -p${PASS} --opt --flush-logs --single-transaction \
--all-databases <% if @backupcompress %>| bzcat -zc <% end %>> ${DIR}/mysql_backup_`date +%Y%m%d-%H%M%S`.sql<% if @backupcompress %>.bz2<% end %>
set -o pipefail
mysqldump -u${USER} -p${PASS} --opt --flush-logs --single-transaction \
--all-databases <% if @backupcompress %>| bzcat -zc <% end %>> ${DIR}/${PREFIX}`date +%Y%m%d-%H%M%S`.sql<% if @backupcompress %>.bz2<% end %>
if [ $? -eq 0 ] ; then
find "${DIR}/" -maxdepth 1 -type f -name "${PREFIX}*.sql*" -mtime +${ROTATE} -print0 | xargs -0 -r rm -f
fi