Files
Random_Ansible_Stuff/playbooks/roles/mysql_backup/tasks/main.yml
T
2026-10-17 23:12:02 -04:00

65 lines
2.1 KiB
YAML

---
- name: Ensure backup rules contains the necessary fields
ansible.builtin.fail:
msg: "You must define {{ backup_rule_checker }} in the backup ruleset"
when: not mysql_backup_rules[backup_rule_checker] is defined
loop:
- target
- target_port
- target_username
- target_password
- database_name
- backup_dir
- backup_name_prefix
- max_backups_kept
loop_control:
loop_var: backup_rule_checker
- name: Ensure necessary packages are installed
ansible.builtin.package:
name:
- "python3-PyMySQL"
- "mysql"
state: present
- name: Make sure backup dir exists
ansible.builtin.file:
path: "{{ mysql_backup_rules['backup_dir'] }}"
state: directory
recurse: true
- name: Take a backup of the specified database
ansible.mysql.mysql_db:
name: "{{ mysql_backup_rules['database_name'] }}"
state: dump
target: "{{ mysql_backup_rules['backup_dir'] }}/{{ mysql_backup_rules['backup_name_prefix'] }}_{{ now().strftime('%Y%m%d%H%M%S') }}.sql.gz"
login_host: "{{ mysql_backup_rules['target'] }}"
login_port: "{{ mysql_backup_rules['target_port'] }}"
login_user: "{{ mysql_backup_rules['target_username'] }}"
login_password: "{{ mysql_backup_rules['target_password'] }}"
- name: Find all files that start with the backup_name_prefix
ansible.builtin.find:
paths: "{{ mysql_backup_rules.backup_dir }}"
patterns: "{{ mysql_backup_rules.backup_name_prefix }}*"
register: all_backup_files
- name: If too many backups kept
when: all_backup_files.files | length > mysql_backup_rules.max_backups_kept
block:
- name: Get the oldest file paths
ansible.builtin.set_fact:
oldest_file_paths: >-
{{ (all_backup_files.files | sort(attribute='mtime'))[:all_backup_files.files | length - mysql_backup_rules.max_backups_kept] |
map(attribute='path') | list }}
- name: Remove the files
ansible.builtin.file:
path: "{{ old_file_to_delete }}"
state: absent
loop: "{{ oldest_file_paths }}"
loop_control:
loop_var: old_file_to_delete