From a42b035e106ea8fa7a906d8a5a18cac593366c86 Mon Sep 17 00:00:00 2001 From: Adar Nimrod <nimrod@shore.co.il> Date: Sun, 1 Nov 2015 22:01:57 +0200 Subject: [PATCH] Universal backup script (doesn't have to know about databases before running). --- files/backup.sh | 21 +++++++++++++++++++++ tasks/main.yml | 16 +++++++++++----- templates/mysql.j2 | 2 -- 3 files changed, 32 insertions(+), 7 deletions(-) create mode 100644 files/backup.sh delete mode 100644 templates/mysql.j2 diff --git a/files/backup.sh b/files/backup.sh new file mode 100644 index 0000000..5b34c25 --- /dev/null +++ b/files/backup.sh @@ -0,0 +1,21 @@ +#!/bin/sh -e +# Back up all databases, each to a seperate file. + +backup() { + mysqldump --defaults-file=/etc/mysql/debian.cnf \ + --single-transaction \ + --force \ + --result-file=/var/backups/mysql_$1.sql $1 +} + +# TODO: Find a way to remove table formatting from this command. +#alias show='mysqlshow --defaults-file=/etc/mysql/debian.cnf' +alias show="mysql --defaults-file=/etc/mysql/debian.cnf -e 'show databases;'" + +# The reason for dropping the first 4 lines is that the first line is the +# heading and 3 following lines are databases internal to MySQL and thus their +# backup is not needed. +for database in $(show | tail -n+5) +do + backup $database +done diff --git a/tasks/main.yml b/tasks/main.yml index d20fcad..f8cb0c4 100644 --- a/tasks/main.yml +++ b/tasks/main.yml @@ -24,23 +24,29 @@ - cron - name: Create database + when: mysql_database is defined mysql_db: + login_user: root + login_password: '{{ mysql_root_password }}' collation: utf8_general_ci encoding: utf8 name: '{{ mysql_database }}' state: present - name: Create account + when: mysql_user is defined and mysql_database is defined mysql_user: + login_user: root + login_password: '{{ mysql_root_password }}' name: '{{ mysql_user }}' - password: '{{ mysql_password }}' + password: '{{ mysql_password|default(omit) }}' priv: '{{ mysql_database }}.*:SELECT,INSERT,UPDATE,DELETE,CREATE,INDEX' state: present - name: Add daily backup job - template: - src: mysql.j2 - dest: '/etc/cron.daily/mysql_{{ mysql_database }}' + copy: + src: backup.sh + dest: /etc/cron.daily/mysql owner: root group: root - mode: '0700' + mode: '0755' diff --git a/templates/mysql.j2 b/templates/mysql.j2 deleted file mode 100644 index 2867b90..0000000 --- a/templates/mysql.j2 +++ /dev/null @@ -1,2 +0,0 @@ -#!/bin/sh -e -mysqldump --user root --password {{ mysql_root_password }} --single-transaction --force {{ mysql_database }} > /var/backups/mysql_{{ mysql_database }}.sql -- GitLab