首页 > 解决方案 > Ansible删除带有通配符/正则表达式/ glob的文件,但有异常

问题描述

我想根据通配符删除文件,但还要向规则添加例外。

- hosts: all
  tasks:
  - name: Ansible delete file wildcard
    find:
      paths: /etc/wild_card/example
      patterns: "*.txt"
      use_regex: true
    register: wildcard_files_to_delete

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

例如,我想排除一个名为“important.txt”的文件。我怎样才能做到这一点?

标签: ansible

解决方案


只需在when删除文件的任务中添加条件即可。例如,类似:

  - name: Ansible remove file wildcard
    file:
      path: "{{ item.path }}"
      state: absent
    when: item.path != '/etc/wild_card/example/important.txt'
    with_items: "{{ wildcard_files_to_delete.files }}"

这将跳过特定文件。如果您有要跳过的文件列表,您可以这样做:

  - name: Ansible remove file wildcard
    file:
      path: "{{ item.path }}"
      state: absent
    when: item.path not in files_to_skip
    with_items: "{{ wildcard_files_to_delete.files }}"
    vars:
      files_to_skip:
        - /etc/wild_card/example/important.txt
        - /etc/wild_card/example/saveme.txt

如果您想根据某种模式保留文件,您可以使用 ansiblematchsearch测试:

  - name: Ansible remove file wildcard
    file:
      path: "{{ item.path }}"
      state: absent
    when: item.path is not search('important.txt')
    with_items: "{{ wildcard_files_to_delete.files }}"

推荐阅读