main.yml 1.5 KB

123456789101112131415161718192021222324252627282930313233
  1. # create user 'mysql-backup'@localhost identified with auth_socket;
  2. # grant select, lock tables, show view on *.* to 'mysql-backup'@localhost;
  3. - name: generate commands
  4. set_fact:
  5. # escape %
  6. # $command .= ' | sed \'s/ AUTO_INCREMENT=[0-9]*\b//\'';
  7. backup_command: |-
  8. target_path="{{item.target_dir_path}}/$(date -u +'\%Y-\%m-\%dT\%H:\%M:\%SZ').sql"; previous_path="{{item.target_dir_path}}/$(ls --sort=time --format=single-column "{{item.target_dir_path}}" | head --lines 1)";
  9. {%- if item.source_host is defined %}
  10. ssh
  11. {%- if item.ssh_key_path is defined %}
  12. -o IdentityFile='{{item.ssh_key_path}}'
  13. {%- endif %}
  14. {%- if item.ssh_user is defined %}
  15. -o User={{item.ssh_user}}
  16. {%- endif %}
  17. {{item.source_host}}
  18. {%- endif %}
  19. /usr/bin/mysqldump --opt --order-by-primary --skip-dump-date {{item.database}} | sed 's$),($),\n($g' >"$target_path"; [ "$previous_path" ] && cmp --quiet "$previous_path" "$target_path" && rm "$target_path"
  20. with_items: '{{mysql_backups}}'
  21. register: mysql_backup_commands
  22. - name: setup cron jobs
  23. blockinfile:
  24. dest: '/etc/crontab'
  25. marker: '# ANSIBLE MYSQL BACKUPS {mark}'
  26. block: |-
  27. {% for backup in mysql_backup_commands.results %}
  28. {% for backup_job in backup.item.cron_jobs %}
  29. {{backup_job.minute}} {{backup_job.hour}} * * * {{backup.item.local_user}} {{backup.ansible_facts.backup_command}}
  30. {% endfor %}
  31. {% endfor %}
  32. become: yes