求助:我的Ansible脚本归档文件为何丢失最上层目录?
问题原因
你遇到的问题是因为archive模块默认会以每个文件的直接父目录作为归档的根路径,当你传入包含完整路径的文件列表时,它会自动剥离掉最上层的Dfile目录,只保留文件相对于其父目录的结构。
解决方案
只需在archive模块中添加root_dir参数,指定要保留的根目录(即Dfile所在的上级目录),就能完整保留你想要的目录结构。
修改后的脚本片段
tasks: - name: 递归查找符合条件的文件/目录 find: paths: "{{ source }}" file_type: any patterns: "{{ type_file }}" age: "{{ days }}d" recurse: true register: output - block: # 优化:直接用map生成文件路径列表,无需循环set_fact - name: 生成待归档文件列表 set_fact: files_to_archive: "{{ output.files | map(attribute='path') | list }}" - name: 执行归档操作 archive: path: "{{ files_to_archive }}" dest: "{{ destination }}/backup.tar.gz" format: gz force_archive: yes # 指定根目录为source的上级目录,保留最上层的Dfile结构 root_dir: "{{ source | dirname }}"
说明
root_dir: "{{ source | dirname }}"会自动获取source的父目录:- 如果
source是相对路径(比如Dfile),dirname会返回当前目录(.),归档时会保留Dfile/efile/xxx.sh的完整结构; - 如果
source是绝对路径(比如/opt/Dfile),dirname会返回/opt,归档后依然会保留Dfile目录层级。
- 如果
用
map(attribute='path')替代循环set_fact是更简洁的写法,能直接从output.files中提取所有文件路径生成列表。
内容的提问来源于stack exchange,提问作者Warrior
相关产品推荐
相关产品推荐

