You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:我的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 09:33:12