Ansible-删除大量单个文件

时间:2018-08-01 17:45:20

标签: ansible ansible-2.x

我想从其他文件夹中删除垃圾文件。 (是的,几个模块的程序员草率,没有以正确的方式清理,但是没关系...)。

在我的Ansible剧本中,我执行以下简单任务来删除早于1h且没有特定名称(模式正则表达式)的文件。这就是为什么我不能简单地清除两个文件夹的原因。较年轻的文件需要保留,并且某些文件不可触摸(由模式指定)。

- name: cleanup | find temporary files for removal
  find:
    paths: /var/xx/yy/temporary/
    recurse: no
    file_type: file
    age: 1h
    age_stamp: mtime
    patterns:
      - '^.*(?<!index\.html)$'
    use_regex: yes
  register: xxyy_temporary_files

- name: cleanup | find public/temporary files for removal
  find:
    paths: /var/zzz/public/temporary/
    recurse: yes
    file_type: any
    age: 1h
    age_stamp: mtime
    patterns:
      - '^.*(?<!index\.html)$'
    use_regex: yes
  register: zzz_public_temporary_files

- name: cleanup | remove garbage files
  file:
    path: "{{ item.path }}"
    state: absent
  with_items:
    - "{{ xxyy_temporary_files.files }}"
    - "{{ zzz_public_temporary_files.files }}"
  loop_control:
    label: "{{ item.path }}"

所以:我有两个事实收集要删除的文件。 然后,我使用Ansible文件模块将其删除。

问题:文件和文件夹有数千个。获取删除内容的列表仅需几秒钟。但是Ansible然后需要年龄才能完成第三项任务。

有没有办法更快地完成此任务?我的意思是像只一次调用文件模块。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

使用Ansibles命令模块重写(如果有人遇到此问题并寻找类似的内容):

- name: cleanup | remove old temporary files
  command: "find {{ item }} -type f -mmin +30 -not -name \"index.html\" -not -name \".htaccess\" -print -delete -maxdepth 1"
  register: xxx_old_tmp_files
  changed_when: xxx_old_tmp_files.stdout != ""
  with_items:
    - /var/xxx/temporary/

- name: cleanup | remove old public/temporary files
  command: "find {{ item }} -type f -mmin +30 -not -name \"index.html\" -print -delete"
  register: yyy_old_pubtmp_files
  changed_when: yyy_old_pubtmp_files.stdout != ""
  with_items:
    - /var/yyy/public/temporary/

- name: cleanup | remove old empty public/temporary folders
  command: "find {{ item }} -type d -mmin +30 -empty -print -delete"
  register: zzz_old_pubtmp_empty_folders
  changed_when: zzz_old_pubtmp_empty_folders.stdout != ""
  with_items:
    - /var/zzz/public/temporary/
相关问题