Implement borg backup role.

This commit is contained in:
Andreas B. Mundt 2020-01-19 18:51:58 +01:00
parent 985cc477b5
commit 004919824c
8 changed files with 129 additions and 2 deletions

View file

@ -0,0 +1,8 @@
borg_pwd: "{{ lookup('password', '/tmp/borg.pwd length=24') }}"
borg_pwd_file: "/root/borg.pwd"
borg_key_backup: "/root/borg-key.backup"
## alternative: "ssh://user@host:port/path/to/repo"
backup_repo: "/var/backups/mnt/backup/borg"
backup_opts: "--exclude-caches"

View file

@ -0,0 +1,6 @@
[Unit]
Description=Run backup script
[Service]
Type=simple
ExecStart=/usr/local/bin/backup

View file

@ -0,0 +1,10 @@
[Unit]
Description=Run backup script daily
[Timer]
OnCalendar=*-*-* 4:00:00
Persistent=true
AccuracySec=15min
[Install]
WantedBy=timers.target

View file

@ -0,0 +1,6 @@
- name: enable backup.service and .timer
systemd:
name: backup.timer
state: started
enabled: True
listen: "enable backup.timer"

View file

@ -0,0 +1,32 @@
- name: install borg
apt:
name: borgbackup
state: latest
- name: check if borg password is available
stat: path="{{ borg_pwd_file }}"
register: borg
- name: dump borg password
shell: echo -n "{{ borg_pwd }}" > "{{ borg_pwd_file }}" ; chmod 0600 "{{ borg_pwd_file }}"
no_log: True
when: not borg.stat.exists
- name: provide backup script
template:
src: "backup"
dest: "/usr/local/bin/backup"
mode: "0750"
- name: provide backup.service and .timer
copy:
src: "{{ item }}"
dest: "/etc/systemd/system/{{ item }}"
with_items:
- backup.service
- backup.timer
notify: "enable backup.timer"
- name: run first backup
command: /usr/local/bin/backup
when: not borg.stat.exists

43
roles/backup/templates/backup Executable file
View file

@ -0,0 +1,43 @@
#!/bin/bash
set -eu
REPOSITORY="{{ backup_repo }}"
BACKUP=({{ backup_dirs|join(' ') }})
EXTRAOPTIONS=({{ backup_opts }})
export BORG_PASSCOMMAND="cat {{ borg_pwd_file }}"
MOUNTED=""
MNT="$(echo "$REPOSITORY" | sed "s|\(^.*/mnt\).*|\1|")"
if grep -q "$MNT" /etc/fstab ; then
[ -d "$REPOSITORY" ] || mount -v "$MNT" && MOUNTED="TRUE"
fi
if [ ! -d "$REPOSITORY" ] ; then
mkdir -vp --mode=0750 "$REPOSITORY"
borg init --encryption=repokey "$REPOSITORY"
borg key export "$REPOSITORY" "{{ borg_key_backup }}"
fi
if [ -e "{{ nc_dir }}/config/config.php" ] ; then
NCDB="{{ data_dir }}/nextcloud-database.dump"
sudo -u www-data /usr/bin/php {{ nc_dir }}/occ maintenance:mode --on
PW="$(grep dbpassword {{ nc_dir }}/config/config.php | \
sed -e "s/\W*'dbpassword' => '//" -e "s/',$//")"
echo -n "Dumping data base into '$NCDB' … "
mysqldump --single-transaction -h localhost -u nextcloud -p"$PW" nextcloud > "$NCDB"
chmod 600 "$NCDB"
echo "done."
fi
ARCHIVE="$(date +%Y-%m-%d-%H:%M)"
echo "Backup ${BACKUP[@]} to $REPOSITORY."
borg create -v "${EXTRAOPTIONS[@]}" "$REPOSITORY::$ARCHIVE" "${BACKUP[@]}"
if [ -e "{{ nc_dir }}/config/config.php" ] ; then
sudo -u www-data /usr/bin/php {{ nc_dir }}/occ maintenance:mode --off
fi
if [ "$MOUNTED" = "TRUE" ] ; then
umount -v "$MNT"
fi