Delete all old files, but keep newest 4 files using ansible-playbook

倾然丶 夕夏残阳落幕 提交于 2021-01-28 22:14:16

问题


I would like to delete all old files, and keep newest 4 files. The output isn't what i expected. Even i use absent on file modules, but it doesn't delete the files.

My files are here

# ls -l /home/tomcat/backup
total 0
-rw-r--r-- 1 root root 0 Mar  3 14:21 1
-rw-r--r-- 1 root root 0 Mar  3 14:21 2
-rw-r--r-- 1 root root 0 Mar  3 14:21 3
-rw-r--r-- 1 root root 0 Mar  3 14:21 4
-rw-r--r-- 1 root root 0 Mar  3 14:21 5
-rw-r--r-- 1 root root 0 Mar  3 14:21 6
-rw-r--r-- 1 root root 0 Mar  3 14:21 as
-rw-r--r-- 1 root root 0 Mar  3 14:21 asd
-rw-r--r-- 1 root root 0 Mar  3 14:21 df
-rw-r--r-- 1 root root 0 Mar  3 14:21 fas
-rw-r--r-- 1 root root 0 Mar  3 14:21 y6

ansible.yml

- name: Prerequsite Deployement | Get first 4 files
  shell: "ls -t {{ item.path }}/{{ item.filename }} | tail -n +4"
  with_items:
    - { path: /home/tomcat/backup, filename: "*" }
  register: files_matched
  tags: prerequsite_deployment

- debug:
    msg: "{{item.stdout_lines}}"
  with_items: "{{files_matched.results}}"
  tags: prerequsite_deployment

- name: Prerequsite Deployement | Clean up path
  file:
    path: "{{item.stdout_lines}}"
    state: absent
  with_items:
    - "{{files_matched.results}}"
  tags: prerequsite_deployment

the result ouput

# ls -l /home/tomcat/backup
total 0
-rw-r--r-- 1 root root 0 Mar  3 14:21 1
-rw-r--r-- 1 root root 0 Mar  3 14:21 2
-rw-r--r-- 1 root root 0 Mar  3 14:21 3
-rw-r--r-- 1 root root 0 Mar  3 14:21 4
-rw-r--r-- 1 root root 0 Mar  3 14:21 5
-rw-r--r-- 1 root root 0 Mar  3 14:21 6
-rw-r--r-- 1 root root 0 Mar  3 14:21 as
-rw-r--r-- 1 root root 0 Mar  3 14:21 asd
-rw-r--r-- 1 root root 0 Mar  3 14:21 df
-rw-r--r-- 1 root root 0 Mar  3 14:21 fas
-rw-r--r-- 1 root root 0 Mar  3 14:21 y6

My expected result output

# ls -l /home/tomcat/backup
total 0
-rw-r--r-- 1 root root 0 Mar  3 14:21 1
-rw-r--r-- 1 root root 0 Mar  3 14:21 2
-rw-r--r-- 1 root root 0 Mar  3 14:21 3
-rw-r--r-- 1 root root 0 Mar  3 14:21 4

回答1:


The attribute mtime in the dictionaries listed in the registered result.files can be used to sort the files. For example

  - find:
      paths: dir1
      recurse: true
    register: result

  - set_fact:
      my_files: "{{ result.files|
                    sort(attribute='mtime')|
                    map(attribute='path')|
                    list }}"

Optionally list the files but the last (newest) 4 files

  - debug:
      var: item
    loop: "{{ my_files[0:-3] }}"

Delete the files if this is what you want

  - file:
      state: absent
      path: "{{ item }}"
    loop: "{{ my_files[0:-3] }}"


来源:https://stackoverflow.com/questions/60503204/delete-all-old-files-but-keep-newest-4-files-using-ansible-playbook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!