下面的代码只删除它在web目录中的第一个文件。我想删除web目录中的所有文件和文件夹,并保留web目录。我该怎么做呢?

- name: remove web dir contents
    file: path='/home/mydata/web/{{ item }}' state=absent
    with_fileglob:
      - /home/mydata/web/*

注意:我已经尝试了rm -rf使用命令和shell,但他们不工作。也许我用错了。

任何正确方向上的帮助都将不胜感激。

我使用ansible 2.1.0.0


当前回答

使用壳模块(也是幂等的):

- shell: /bin/rm -rf /home/mydata/web/*

如果有点/隐藏文件:

- shell: /bin/rm -rf /home/mydata/web/* /home/mydata/web/.*

如果你不关心创建日期和所有者/权限,最干净的解决方案:

- file: path=/home/mydata/web state=absent
- file: path=/home/mydata/web state=directory

其他回答

我已经写了一个自定义ansible模块来清理基于多个过滤器的文件,如年龄,时间戳,glob模式等。

它也兼容一个可靠的旧版本。可以在这里找到。

这里有一个例子:

- cleanup_files:
  path_pattern: /tmp/*.log
  state: absent
  excludes:
    - foo*
    - bar*

下面对我很有用,

- name: Ansible delete html directory
  file:
   path: /var/www/html
   state: directory

假设您一直在Linux中,尝试查找cmd。

- name: Clean everything inside {{ item }}
  shell: test -d {{ item }} && find {{ item }} -path '{{ item }}/*' -prune -exec rm -rf {} \;
  with_items: [/home/mydata/web]

这将清除隐藏在/home/mydata/web下的文件/文件夹

使用文件glob也可以。你发布的代码有语法错误。我已经修改和测试这应该工作。

- name: remove web dir contents
  file:
    path: "{{ item }}"
    state: absent
  with_fileglob:
    - "/home/mydata/web/*"

下面是投票最多的答案(我无法编辑,因为“编辑队列已满”):

- name: Delete content & directory
  file:
    state: absent
    path: /home/mydata/web/

- name: Re-create the directory
  file:
    state: directory
    path: /home/mydata/web/