下面的代码只删除它在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


当前回答

- name: Files to delete search
  find:
    paths: /home/mydata/web/
    file_type: any
  register: files_to_delete

- name: Deleting files to delete
  file:
    path: '{{ item.path }}'
    state: absent
  with_items: "{{ files_to_delete.files }}"

其他回答

假设您一直在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下的文件/文件夹

根据所有的评论和建议创建了一个全面的重新检查和故障安全实现:

# collect stats about the dir
- name: check directory exists
  stat:
    path: '{{ directory_path }}'
  register: dir_to_delete

# delete directory if condition is true
- name: purge {{directory_path}}
  file:
    state: absent
    path: '{{ directory_path  }}'
  when: dir_to_delete.stat.exists and dir_to_delete.stat.isdir

# create directory if deleted (or if it didn't exist at all)
- name: create directory again
  file:
    state: directory
    path: '{{ directory_path }}'
  when: dir_to_delete is defined or dir_to_delete.stat.exist == False

下面对我很有用,

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

这就是我想到的:

- name: Get directory listing
  find:
    path: "{{ directory }}" 
    file_type: any
    hidden: yes
  register: directory_content_result

- name: Remove directory content
  file:
    path: "{{ item.path }}" 
    state: absent
  with_items: "{{ directory_content_result.files }}" 
  loop_control:
    label: "{{ item.path }}" 

首先,我们用查找,设置获取目录列表

File_type转换为any,这样我们就不会错过嵌套目录和链接 隐藏为yes,所以我们不会跳过隐藏文件 另外,不要将递归设置为yes,因为这不仅没有必要,而且可能会增加执行时间。

然后,我们用文件模块遍历这个列表。它的输出有点啰嗦,因此输入loop_control。标签将帮助我们限制输出(在这里找到这个建议)。


但我发现以前的解决方案有点慢,因为它迭代的内容,所以我去:

- name: Get directory stats
  stat:
    path: "{{ directory }}"
  register: directory_stat

- name: Delete directory
  file:
    path: "{{ directory }}"
    state: absent

- name: Create directory
  file:
    path: "{{ directory }}"
    state: directory
    owner: "{{ directory_stat.stat.pw_name }}"
    group: "{{ directory_stat.stat.gr_name }}"
    mode: "{{ directory_stat.stat.mode }}"

使用stat获取目录属性 删除目录 重新创建具有相同属性的目录。

这对我来说已经足够了,但是如果你愿意,你也可以添加属性。

我希望确保find命令只删除目录内的所有内容,并保持目录完整,因为在我的示例中,目录是一个文件系统。当尝试删除文件系统时,系统将生成一个错误,但这不是一个好的选择。我使用壳选项,因为这是唯一的工作选项,我发现这个问题到目前为止。

我做了什么:

编辑hosts文件,放入一些变量:

[all:vars]
COGNOS_HOME=/tmp/cognos
find=/bin/find

并创建一个剧本:

- hosts: all
  tasks:
  - name: Ansible remove files
    shell: "{{ find }} {{ COGNOS_HOME }} -xdev -mindepth 1 -delete"

这将删除COGNOS_HOME变量目录/文件系统中的所有文件和目录。"-mindepth 1"选项确保不会触及当前目录。