Ansible - remove old backup files

Viewed 28

For several modules, Ansible has a backup option.

- name: template a file w backup option
  template:
    src: my_file.j2
    dest: /tmp/
    backup: true

Each time Ansible runs, and there is a change for that file, Ansible creates a backup file in the respective folder. In the end, there will be many backup files.

Q: Is there an elegant Ansible solution to remove these backup files for which it placed the file/template? E.g. keep only the latest 3 backup files?

1 Answers

You can:

  • Use the find module to generate a list of backup files
  • Use the sort filter to sort them by modification time
  • Use list slicing to select all but the last <N>
  • Use the file module to delete old backups

So, something like:

- hosts: localhost
  gather_facts: false
  tasks:
    - template:
        src: myfile.j2
        dest: ./myfile
        backup: true

    - find:
        paths: .
        patterns: "myfile.[0-9]*"
      register: files

    - file:
        path: "{{ item.path }}"
        state: absent
      loop: >-
        {{ (files.files|sort(attribute="mtime"))[:-2] }}

You can run this playbook in a loop to demonstrate it:

for i in {1..10}; do
  ansible-playbook -e iteration=$i playbook.yaml
done

You'll see that it only ever keeps the most recent two backups .

Related