在Ansible中,与find -exec cp
和文件扩展名过滤相对应的是copy
模块和with_fileglob
循环。下面是一个使用Ansible实现类似功能的代码示例:
- name: 查找并复制特定文件
hosts: all
tasks:
- name: 查找特定文件
find:
paths: /path/to/search
file_type: file
patterns: "*.txt" # 文件扩展名过滤
register: found_files
- name: 复制文件
copy:
src: "{{ item.path }}"
dest: /path/to/destination/{{ item.name }}
with_fileglob:
- "{{ found_files.files }}"
在这个示例中,首先使用find
模块查找指定目录下的文件,并使用file_type
参数指定只搜索文件而不包括目录。patterns
参数可以使用通配符来过滤文件扩展名,这里使用"*.txt"
表示只找到扩展名为.txt
的文件。register
参数将搜索结果保存到变量found_files
中。
然后使用copy
模块和with_fileglob
循环来复制找到的文件。with_fileglob
参数接受一个文件列表,这里使用found_files.files
作为文件列表。item.path
表示文件的路径,item.name
表示文件的名称。src
参数指定源文件路径,dest
参数指定目标文件路径,这里将目标文件放在/path/to/destination/
目录下,并保持文件名不变。
通过这种方式,可以在Ansible中实现类似于find -exec cp
和文件扩展名过滤的功能。