下面的代码只删除它在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: 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: remove web dir contents
  command:
    cmd: "find . -path '*/*' -delete -print"
    chdir: "/home/mydata/web/"
  register: web_files_list
  changed_when: web_files_list.stdout | length > 0

因为它是:

简单的 幂等 快

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

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

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

而Ansible仍在讨论实现state = empty https://github.com/ansible/ansible-modules-core/issues/902

my_folder: "/home/mydata/web/"
empty_path: "/tmp/empty"


- name: "Create empty folder for wiping."
  file:
    path: "{{ empty_path }}" 
    state: directory

- name: "Wipe clean {{ my_folder }} with empty folder hack."
  synchronize:
    mode: push

    #note the backslash here
    src: "{{ empty_path }}/" 

    dest: "{{ nl_code_path }}"
    recursive: yes
    delete: yes
  delegate_to: "{{ inventory_hostname }}"

不过请注意,无论如何,使用synchronize你应该能够正确地同步你的文件(使用delete)。

如果你使用Ansible >= 2.3(文件和dirs之间的区别不再需要了),只是一个简单的复制和粘贴ThorSummoners的模板。

- name: Collect all fs items inside dir
  find:
    path: "{{ target_directory_path }}"
    hidden: true
    file_type: any
  changed_when: false
  register: collected_fsitems
- name: Remove all fs items inside dir
  file:
    path: "{{ item.path }}"
    state: absent
  with_items: "{{ collected_fsitems.files }}"
  when: collected_fsitems.matched|int != 0

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

# 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