首页 > 解决方案 > Ansible:删除文件和文件夹,同时排除一些

问题描述

在我的 Ansible Playbook 中,我想要一个从应用程序目录中删除旧文件和文件夹的任务。这个原本简单的任务的转折是需要保留一些文件或文件夹。想象一下这样的事情:

/opt/application
  - /config
    - *.properties
    - special.yml
  - /logs
  - /bin
  - /var
    - /data
    - /templates

假设我想/logs完全保留,/var/data并且/config我想保留special.yml

(我目前无法提供确切的代码,因为我对此感到沮丧,在冷静下来后,我现在正在家里写这个问题)

我的想法是有两个排除列表,一个包含文件夹,一个包含文件。然后我使用该find模块首先将应用程序目录中的文件夹放入一个变量中,并将其余文件相同的放入另一个变量中。file之后,我想使用该模块删除不在排除列表中的每个文件夹和文件。

(伪 YML,因为我在 Ansible 中还不够流利,所以我可以编写一个结构合理的示例;不过它应该足够接近)

file:
  path: "{{ item.path }}"
  state: absent
with_items: "{{ found_files_list.files }}"
when: well, that is the big question

我不知道如何正确构造该when子句。甚至有可能这样吗?

标签: ansible

解决方案


我不相信文件模块有 when 子句。但是您可能可以通过以下方式实现所需的功能:

- name: Find /opt/application all directories, exclude logs, data, and config
  find:
    paths: /opt/application
    excludes: 'logs,data,config'
  register: files_to_delete

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

我希望这是你需要的。


推荐阅读