如何用Ansible获取目录文件列表并删除另一目录同名文件?
修复Ansible删除同名文件的Playbook问题
你的Playbook未生效的核心原因是:find模块返回的files_to_delete.files是字典列表,每个item包含文件的完整路径、文件名等详细信息,直接拼接{{item}}会生成无效路径(比如/root/test2/{'name': 'test.txt', 'path': '/root/test/test.txt', ...}),导致无法匹配目标文件。
修复方案(两种可选)
方案1:提取文件名后循环
通过map过滤器从字典中提取name字段,得到纯文件名列表再循环:
- hosts: all tasks: - name: 获取/root/test目录下的文件列表 find: paths: /root/test file_type: file # 仅匹配文件,排除目录(可选,根据需求调整) register: files_to_delete - name: 删除/root/test2目录中的同名文件 file: path: /root/test2/{{ item }} state: absent with_items: "{{ files_to_delete.files | map(attribute='name') | list }}"
方案2:循环中直接调用字典字段
直接在循环里引用字典的name属性,避免额外的过滤器处理:
- hosts: all tasks: - name: 获取/root/test目录下的文件列表 find: paths: /root/test file_type: file register: files_to_delete - name: 删除/root/test2目录中的同名文件 file: path: /root/test2/{{ item.name }} state: absent loop: "{{ files_to_delete.files }}" # 新版Ansible推荐用loop替代with_items
额外说明
- 如果需要同时删除同名目录,去掉
file_type: file参数即可; - 执行前可以加
--check参数做预检查,确认要删除的文件路径是否正确。
内容的提问来源于stack exchange,提问作者Milad Akhlaghi
相关产品推荐
相关产品推荐

