gpt4 book ai didi

linux - 删除所有旧文件,但使用 ansible-playbook 保留最新的 4 个文件

转载 作者:行者123 更新时间:2023-12-03 08:48:18 29 4
gpt4 key购买 nike

我想删除所有旧文件,并保留最新的 4 个文件。输出不是我所期望的。即使我在文件模块上使用不存在,但它不会删除文件。

我的文件在这里

# 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

结果输出

# 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中列出的字典属性mtimesort文件。例如

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

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

(可选)列出除最后(最新)4 个文件之外的文件

  - debug:
var: my_files[0:-4]

并删除文件(如果这是您想要的)

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

关于linux - 删除所有旧文件,但使用 ansible-playbook 保留最新的 4 个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60503204/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com