--- - name: Ensure backup rules contains the necessary fields ansible.builtin.fail: msg: "You must define {{ backup_rule_checker }} in the backup ruleset" when: not backup_rules[backup_rule_checker] is defined loop: - container_name - directories_to_backup - backup_dir - backup_name_prefix - max_backups_kept loop_control: loop_var: backup_rule_checker - name: Make sure backup dir exists ansible.builtin.file: path: "{{ backup_rules['backup_dir'] }}" state: directory recurse: true - name: Stop the running container community.docker.docker_container: name: "{{ backup_rules.container_name }}" state: stopped - name: Archive necessary directories community.general.archive: path: "{{ backup_rules.directories_to_backup }}" dest: >- {{ backup_rules.backup_dir }}/{{ backup_rules.backup_name_prefix }}_ {{ now().strftime("%Y%m%d%H%M%S") }}.tar.gz format: gz async: 3600 poll: 60 - name: Start the stopped container community.docker.docker_container: name: "{{ backup_rules.container_name }}" state: started - name: Find all files that start with the backup_name_prefix ansible.builtin.find: paths: "{{ backup_rules.backup_dir }}" patterns: "{{ backup_rules.backup_name_prefix }}*" register: all_backup_files - name: If too many backups kept when: all_backup_files.files | length > 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 - 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