下面的代码只删除它在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: ls -1 /some/dir
  register: contents

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

其他回答

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

- 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

我真的不喜欢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: Get directory listing
  become: yes
  find:
    paths: /applications/cache
    patterns: '*'
    hidden: yes
  register: directory_content_result

- name: Remove directory content
  become: yes
  file:
    path: "{{ item.path }}"
    state: absent
  with_items: "{{ directory_content_result.files }}"
  - 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

我希望确保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"选项确保不会触及当前目录。