我有一个要求,我需要递归地搜索目录中的某些文件。然后在每个匹配的子目录中,获取最新的文件。
假设这是一个目录结构:
现在如您所见,我在子目录 *.txt
和 A
中突出显示了最新的 B
文件,而 C
没有。
我下面的代码将从子目录中获取所有 *.txt
文件。我只是不知道如何只使用 Ansible 获取最新文件并避免使用 shell 脚本。
- name: Ansible find file examples
find:
paths: "/home/sarah/demo/"
patterns: "*txt"
recurse: yes
register: files_matched
- name: Get latest file
set_fact:
latest_file: "{{ files_matched.files | sort(attribute='mtime',reverse=true) }}"
- debug:
msg: "{{ item }}"
with_items: "{{latest_file|map(attribute='path')|list}}"
任何帮助将不胜感激。
答案 0 :(得分:1)
您可以为此创建一个列表,其条件基于列表中已有内容的 dirname
和 dirname
(感谢过滤器 map
的帮助)。
使用剧本:
- hosts: all
gather_facts: no
tasks:
- find:
paths: /home/sarah/demo
patterns: "*.txt"
recurse: yes
register: files_matched
- set_fact:
latest_files: "{{ latest_files | default([]) + [item.path] }}"
loop: "{{ files_matched.files | sort(attribute='mtime', reverse=true) }}"
when: "item.path | dirname not in latest_files | default([]) | map('dirname')"
##
# The loop_control is just there for validation purpose
##
loop_control:
label: "{{ '%Y-%m-%d %H:%M:%S' | strftime(item.mtime) }} {{ item.path }}"
- debug:
var: latest_files
这给了我一个回顾:
PLAY [all] ********************************************************************************************************
TASK [find] *******************************************************************************************************
ok: [localhost]
TASK [set_fact] ***************************************************************************************************
ok: [localhost] => (item=2021-03-15 14:07:10 /home/sarah/demo/B/b1.txt)
ok: [localhost] => (item=2021-03-15 14:06:16 /home/sarah/demo/A/a2.txt)
skipping: [localhost] => (item=2021-03-15 14:06:05 /home/sarah/demo/B/b.txt)
skipping: [localhost] => (item=2021-03-15 14:05:46 /home/sarah/demo/A/a.txt)
skipping: [localhost] => (item=2021-03-15 14:05:38 /home/sarah/demo/A/a1.txt)
TASK [debug] ******************************************************************************************************
ok: [localhost] =>
latest_files:
- /home/sarah/demo/B/b1.txt
- /home/sarah/demo/A/a2.txt
PLAY RECAP ********************************************************************************************************
localhost : ok=3 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
所有这些都再现了您的文件结构:
A:
total 0
-rw-r--r-- 1 root root 0 Mar 15 14:05 a.txt
-rw-r--r-- 1 root root 0 Mar 15 14:05 a1.txt
-rw-r--r-- 1 root root 0 Mar 15 14:06 a2.txt
B:
total 0
-rw-r--r-- 1 root root 0 Mar 15 14:06 b.txt
-rw-r--r-- 1 root root 0 Mar 15 14:07 b1.txt
C:
total 0