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


当前回答

我真的不喜欢rm解决方案,也ansible给你关于使用rm的警告。 因此,这里是如何做到这一点,而不需要rm和ansible警告。

- hosts: all
  tasks:
  - name: Ansible delete file glob
    find:
      paths: /etc/Ansible
      patterns: "*.txt"
    register: files_to_delete

  - name: Ansible remove file glob
    file:
      path: "{{ item.path }}"
      state: absent
    with_items: "{{ files_to_delete.files }}"

来源:http://www.mydailytutorials.com/ansible-delete-multiple-files-directories-ansible/

其他回答

  - name: delete old data and clean cache
    file:
      path: "{{ item[0] }}" 
      state: "{{ item[1] }}"
    with_nested:
      - [ "/data/server/{{ app_name }}/webapps/", "/data/server/{{ app_name }}/work/" ]
      - [ "absent", "directory" ]
    ignore_errors: yes
- name: Delete content & directory
  file:
    state: absent
    path: /home/mydata/web/

注意:这也会删除目录。

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

- 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

这就是我想到的:

- 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获取目录属性 删除目录 重新创建具有相同属性的目录。

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

尝试下面的命令,它应该可以工作

- shell: ls -1 /some/dir
  register: contents

- file: path=/some/dir/{{ item }} state=absent
  with_items: {{ contents.stdout_lines }}