0

Instead of using the Ansible shell or command modules, I am trying to use the find module to delete old backup directories and only keep the latest n backups. Currently, I use the following code to get a list of all the backup directories (so that in a second step I could delete the unwanted ones):

- find:
    paths: "/opt/"
    patterns: "backup_*"
    file_type: "directory"

Unfortunately, I don't see any way of narrowing down the resulting list of directories...

  1. The find module doesn't seem to support sorting... can that be done in any way?
  2. Does Ansible provide any means to manipulate a JSON list... to keep only n elements in a list and remove all others?

Has anyone successfully used the find module for similar purposes?

dokaspar
  • 8,186
  • 14
  • 70
  • 98

1 Answers1

1

You can sort with sort filter

You can task first N elements of a list with [:N] syntax.

- find:
    path: "/tmp/"
    pattern: "file*"
  register: my_files

- debug: msg="{{(my_files.files | sort(attribute='ctime'))[:-3] | map(attribute='path') | list }}"

Sort files by ctime, take all but last three elements, take only path attribute and form a list.

Konstantin Suvorov
  • 65,183
  • 9
  • 162
  • 193
  • Are these commands `sort`, `map` and `list` documented anywhere? I get an error ""template error while templating string: no filter named 'map'" – dokaspar Sep 15 '16 at 06:34
  • also, the `[:-3]` doesn't really do anything... always the full list is printed – dokaspar Sep 15 '16 at 06:41
  • yes, http://jinja.pocoo.org/docs/dev/templates/#list-of-builtin-filters and http://docs.ansible.com/ansible/playbooks_filters.html – Konstantin Suvorov Sep 15 '16 at 07:06