Ansible:如何删除以特定名称开头的文件?

Ansible: How to delete files starting with a specific name?

我是 Ansible 新手。

我有这样一个目录:

home/etc/directory/

其中包含以下文件:

application.yml
application.yml_new
application.yml.12345
etc.yml

我想做的是delete/remove文件

application.yml_new
application.yml.12345

我不想明确命名这些文件,但我想删除所有带有 application.yml 后缀的文件(因为名称因应用程序而略有不同)。

现在我想知道如何做到这一点?

我找到了 file,但我不确定我是否可以用它来做,还是只能用 shell-模块来做?

实现此目的的一种方法是将 find command 与 ansible 中的 file module 结合使用。

像这样:

- name: getfiles
  shell: "find * -name 'application.yml*' ! -name application.yml"
  register: files_to_delete
  args:
    chdir: "/home/admin"

- name: delete files
  file:
    path: "/home/admin/{{item}}"
    state: absent
  with_items: "{{files_to_delete.stdout_lines}}"

首先,我们使用 find 命令搜索文件,并将结果注册到一个变量中。

然后我们可以使用 stdout 行,它是我们要删除的文件名的数组。

注意:因为 find 命令还包含 application.yml 我将其排除。如上例所示

最后,我们可以遍历列表并删除文件。

问:"删除所有后缀为application.yml"

的文件

A:先找到文件。例如,给定树

shell> tree etc/directory
etc/directory/
├── application.yml
├── application.yml.12345
├── application.yml_new
└── etc.yml

0 directories, 4 files

模块 find 完成工作

    - find:
        paths: etc/directory
        patterns: '^application\.yml.+$'
        use_regex: true
      register: result

给予

  result.files|map(attribute='path')|list:
  - etc/directory/application.yml.12345
  - etc/directory/application.yml_new

迭代列表并删除文件

    - file:
        state: absent
        path: "{{ item }}"
      loop: "{{ result.files|map(attribute='path')|list }}"

给予

shell> tree etc/directory
etc/directory/
├── application.yml
└── etc.yml

0 directories, 2 files

Python 正则表达式的解释
patterns: '^application\.yml.+$'
^ ............. matches the beginning of the string
application ... matches the string 'application'
\. ............ matches dot '.'; must be escaped because of dot matches any character
yml ........... matches the string 'yml'
.+ ............ matches one or more of any characters
$ ............. matches the end of the string