? 根据条件查找文件,返回文件列表。文档中已经有很详细的解释,可以用ansible-doc find
查看文档。下面对常用的参数作一些解释,和主要详解后面的案例(找出文件,并对找出的文件做一些操作)。
name
、path
(即用name、path和paths相同)recurse
设置为yes
hidden
设置为yes
any
、directory
、file
、link
file_type=file
的时候才有效use_regex
参数需设置为yes
no
,表示contains
、patterns
、excludes
使用shell通配符;如果指定为yes
,则contains
、patterns
、excludes
使用正则表达式查找符合条件的目录,然后遍历目录,查找符合条件的文件。
执行逻辑
foo
开头和test
开头的目录,首先查找test
开头的目录,把结果存储在register: find_dirctory
中。test
开头的目录(用with_list
遍历),在目录下查找文件名.py
结尾,文件内容包含qwertyuiop
的文件。bar1_1.py
、bar1_2.py
、bar2_1.py
查找目录结构
$ tree ~/test/
├── foo1
│ ├── bar1
│ └── bar2
├── index.html
├── test1
│ ├── bar1_1.py
│ ├── bar1_2.py
│ ├── file1_1
│ ├── foo1_1.txt
│ ├── foo1_2.txt
│ └── foo1_3.txt
└── test2
├── bar2_1.py
├── bar2_2.py
├── bar2_3.py
└── file2_1
8 directories, 11 files
ansible-play脚本结构
$ tree
.
├── inventories
│ └── localhost
├── main.yml
└── roles
└── find
└── tasks
└── main.yml
4 directories, 3 files
inventories/localhost
[servers]
127.0.0.1
[servers:vars]
# 远程用户名
become_user = user_name
# 查找目录
directory_path = "~/test"
main.yml
---
- name: find module test
hosts: servers
become_method: sudo
become: yes
become_user: "{{ become_user }}"
gather_facts: no
roles:
- find
roles/find/tasks/main.yml
---
- name: find directory
find:
paths: "{{ directory_path }}"
file_type: "directory"
recurse: no
patterns: "test*"
register: find_dirctory
- name: find file
find:
paths: "{{ item.path }}"
file_type: "file"
recurse: yes
patterns: "*.py"
contains: ".*qwertyuiop.*"
with_list: "{{ find_dirctory.files }}"
register: find_file
- name: print find file
debug:
msg:
"
{% for i in item.files %}
{{ i.path }}
{% endfor %}
"
with_list: "{{ find_file.results }}"
运行
$ ansible-playbook -i inventories/localhost main.yml
运行结果
"msg": " /home/user_name/test/test2/bar2_1.py "
"msg": " /home/user_name/test/test1/bar1_2.py /home/user_name/test/test1/bar1_1.py "
可以找到bar1_1.py
、bar1_2.py
、bar2_1.py
三个符合条件的文件。
原文:https://www.cnblogs.com/shengmading/p/14524861.html