使用ansible,如何删除目录中指定集之外的所有项?

Chr*_*tze 6 ansible

当然,我可以使用shell命令,但我希望有一种可行的方法来做到这一点,这样我就可以得到"改变/未改变"的响应.

Lar*_*röm 8

这是我的方法:

- name: Capture files to delete
  find:
    paths: /path/to/directory
    file_type: file
    excludes: 
      - "myfirst.file"
      - "mysecond.file"
  register: found_files

- name: Delete files
  file:
    path: "{{ item.path }}"
    state: absent
  with_items: "{{ found_files['files'] }}"
Run Code Online (Sandbox Code Playgroud)


mra*_*agh 2

除了您在评论中发现的内容之外,如果您最终需要执行 shell 命令,您可以使用command带有removes参数 ( doc ) 的模块。如果文件已经(不存在)存在,它将跳过该步骤,这将阻止它报告该changed步骤。但是,您仍然需要像其他答案一样迭代列表。