main.yml 1.3 KB

1234567891011121314151617181920212223242526
  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 -i {{item.ssh_key_path}} {{item.ssh_user}}@{{item.source_host}}
  11. {%- endif %}
  12. /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"
  13. with_items: '{{mysql_backups}}'
  14. register: mysql_backup_commands
  15. - name: setup cron jobs
  16. blockinfile:
  17. dest: '/etc/crontab'
  18. marker: '# ANSIBLE MYSQL BACKUPS {mark}'
  19. block: |-
  20. {% for backup in mysql_backup_commands.results %}
  21. {% for backup_job in backup.item.cron_jobs %}
  22. {{backup_job.minute}} {{backup_job.hour}} * * * {{backup.item.local_user}} {{backup.ansible_facts.backup_command}}
  23. {% endfor %}
  24. {% endfor %}
  25. become: yes