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

Ansible遍历列表字典编写Playbook清理win目录保留local的方法

Ansible 目录清理Playbook实现方案

实现逻辑

整个实现完全通过遍历列表、字典的Ansible标准逻辑完成,不会硬编码任何win开头的目录名,适配后续新增win3、win4等同规则目录的场景:

  • 首先定位/sample路径下所有名称以win开头的一级目录,排除iis、linux、sql等非目标目录,避免误操作
  • 遍历每个命中的win开头目录,收集目录下所有一级子项(包含文件、子目录)
  • 过滤掉名称为local的子项,将剩余内容全部删除,保留win目录本身和内部的local目录

完整Playbook代码

将以下内容保存为cleanup_win_dirs.yml:

---
- name: 清理win开头目录,仅保留local子目录
  hosts: all
  # 若操作目录需要root权限请保留become,否则可注释
  become: yes
  tasks:
    - name: 查找/sample下所有以win开头的一级目录
      ansible.builtin.find:
        paths: /sample
        patterns: 'win*'
        file_type: directory
        depth: 1
      register: win_root_dirs

    - name: 遍历每个win目录,收集除local外的所有待删除子项
      ansible.builtin.find:
        paths: "{{ item.path }}"
        file_type: any
        depth: 1
        excludes: 'local'
      loop: "{{ win_root_dirs.files }}"
      register: pending_delete_items

    - name: 执行删除操作
      ansible.builtin.file:
        path: "{{ single_item.path }}"
        state: absent
      loop: "{{ pending_delete_items.results | map(attribute='files') | flatten }}"
      loop_control:
        loop_var: single_item

使用说明

  • 执行命令:ansible-playbook cleanup_win_dirs.yml,如果是本地操作可加-c local参数指定本地连接
  • 执行前建议做预校验,把最后一步删除任务临时替换为debug任务,打印所有待删除路径,确认无遗漏误判后再执行实际删除,预校验任务示例:
- name: 预校验待删除路径
  ansible.builtin.debug:
    msg: "待删除路径:{{ single_item.path }}"
  loop: "{{ pending_delete_items.results | map(attribute='files') | flatten }}"
  loop_control:
    loop_var: single_item
  • 执行完成后预期结果:
    • /sample/iis、/sample/linux、/sample/sql三个目录完整保留原有结构,无任何改动
    • /sample/win1、/sample/win2目录本身保留,内部仅剩余local目录,其余default、lookup、README、testfile、lookup.csv等内容全部被清理,和要求的目标结构完全一致

内容的提问来源于stack exchange,提问作者majidzandinia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 23:12:34