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

其他回答

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

# 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: 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: 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 }}"

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

- 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/