繁体   English   中英

从 Ansible Playbook 中删除服务器所有目录中的特定文件夹/文件

[英]Delete specific folder/files in all the directories of the server from the Ansible Playbook

我想删除服务器子目录中的所有“测试”文件夹。 如下所示是“测试”文件夹的路径。 主文件夹中有多个目录,因此,我无法在剧本中指定所有路径。

路径: /home/*/test

我为此编写了以下剧本,但它不起作用。

tasks:
   - name: Delete the folder
     file:
       path: "{{ item }}"
       state: absent
     with_items:
       - "/home/*/test"

你能告诉我解决方案吗..

我试过使用 file_glob 但没有用。 我想从所有子目录中删除测试文件夹。

使用模块查找 例如,给定树

shell> tree /tmp/home/
/tmp/home/
├── a
├── b
│   └── test
└── c
    └── test

声明路径列表

  test_dirs: "{{ out.files|map(attribute='path') }}"

然后,任务

    - find:
        paths: /tmp/home
        file_type: directory
        patterns: test
        recurse: true
      register: out

  test_dirs:
  - /tmp/home/c/test
  - /tmp/home/b/test

使用列表删除目录

    - file:
        path: "{{ item }}"
        state: absent
      loop: "{{ test_dirs }}"
shell> tree /tmp/home/
/tmp/home/
├── a
├── b
└── c

用于测试的完整剧本示例

- hosts: localhost vars: test_dirs: "{{ out.files|map(attribute='path') }}" tasks: - find: paths: /tmp/home file_type: directory patterns: test recurse: true register: out - debug: var: test_dirs - file: path: "{{ item }}" state: absent loop: "{{ test_dirs }}"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM