[root@ansible ansible]# more roles/find/tasks/main.yml
---
# tasks file for find
# author: loong576
- name: choose the directory
find:
paths: "{{ directory_path }}"
recurse: no
age:7d
age_amtnp:mtime
file_type: directory
excludes: "{{ exclude_directory }}"
register: find_directory
- name: find in directory
find:
paths: "{{item.path}}"
recurse: yes
contains: "{{ file_contains }}"
hidden: yes
size: "{{ file_size }}"
with_list: "{{find_directory.files}}"
register: find_contains_in_directory
- name: echo find file in directories
debug:
msg:
"{% for i in item.files %}
{{ i.path }}
{% endfor %}"
with_list: "{{find_contains_in_directory.results}}"
when: item.matched != 0
- name: find in files
find:
path: "{{ file_path }}"
file_type: file
excludes: "{{ exclude_file }}"
hidden: yes
contains: "{{ file_contains }}"
register: find_only_file
- name: echo find file in files
debug:
msg: "{{item.path}}"
with_list: "{{find_only_file.files}}"
执行逻辑
指定路径下目录查找
首先选择需要查找的指定路径{{ directory_path }},这里为/opt,选择的时候排除掉不需要的目录{{ exclude_directory }};然后通过循环方式在选择的目录里查找指定内容{{ file_contains }}并输出查到的文件列表。
这里的目录指/opt下的find1和find2,find3被排除在外。
指定路径下文件查找
查找指定路径{{ directory_path }}下所有文件是否包含指定内容{{ file_contains }}并输出文件列表,{{ exclude_file }}文件被排除在外。
这里的文件指test1.txt、.test3.txt,test2.txt被排除在外。
所有的隐藏文件默认被查找'hidden: yes'且找到的文件大小不能超过{{ file_size }}即100M