Tobitor
Tobitor

Reputation: 1508

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

I am new to Ansible.

I have such a directory:

home/etc/directory/

Which contains the following files:

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

What I want to do is to delete/remove the files

application.yml_new
application.yml.12345

I do not want to explicitly name these files but I want to delete all files with a suffix additional to application.yml (since the names are slightly different depending on the application).

Now I am wondering how to do this?

I found the file but I am not sure if I can do this with it or can it be only done with the shell-module?

Upvotes: 3

Views: 5667

Answers (2)

Vladimir Botka
Vladimir Botka

Reputation: 67984

Q: "Delete all files with a suffix additional to application.yml"

A: Find the files first. For example, given the tree

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

0 directories, 4 files

The module find does the job

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

gives

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

Iterate the list and delete the files

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

gives

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

0 directories, 2 files

Explanation of the Python regex
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

Upvotes: 4

Nur1
Nur1

Reputation: 480

One way to achieve this is to use the find command in combination with the file module in ansible.

Like this:

- 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}}"

First, we search for the files by using the find command and register the results in a variable.

Then we are able to use the stdout lines which is an array of the filenames we want to delete.

NOTE: Because the find command also includes the application.yml I exclude it. As seen in the example above

At last, we can loop over the list and delete the files.

Upvotes: 0

Related Questions