删除所有旧文件,但使用ansible-playbook保留最新的4个文件 [英] Delete all old files, but keep newest 4 files using ansible-playbook
本文介绍了删除所有旧文件,但使用ansible-playbook保留最新的4个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想删除所有旧文件,并保留最新的4个文件.输出不是我所期望的.甚至我在文件模块上都不使用它,但是它不会删除文件.
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.
我的文件在这里
# 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
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
结果输出
# 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
我的预期结果输出
# 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
推荐答案
已注册的 result.files
中列出的词典中的属性 mtime
可用于对文件.例如
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 }}"
(可选)列出文件,但列出最后(最新)的4个文件
Optionally list the files but the last (newest) 4 files
- debug:
var: item
loop: "{{ my_files[0:-3] }}"
如果需要,请删除文件
- file:
state: absent
path: "{{ item }}"
loop: "{{ my_files[0:-3] }}"
这篇关于删除所有旧文件,但使用ansible-playbook保留最新的4个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文