1

I have some directories and files inside a directory called dir1 I am trying to empty that directory using the below code

     - name: Clean  path
       file:
          state: absent
          path: "/home/location/dir1"

But it is deleting the dir1 itself, i would like to empty it and keep this dir1, what am i missing here, any help on this would be appreciated.

windowws
  • 373
  • 1
  • 8
  • 20
  • 2
    There are multiple approach on how to achieve this in this question: [Ansible: How to delete files and folders inside a directory?](https://stackoverflow.com/questions/38200732/ansible-how-to-delete-files-and-folders-inside-a-directory). The behaviour as you see it is the intended one, you want the directory to be absent, so it is deleted. – β.εηοιτ.βε Sep 23 '20 at 18:07

3 Answers3

1

To empty a directory you can use the shell module to run rm with a fileglob:

- name: empty directory
  shell: rm -r /home/location/dir1/*

Note that if your directory contains hidden dotfiles, you'll need to explicitly remove those as well:

- name: empty directory containing hidden files
  shell: rm -r /home/location/dir1/* /home/location/dir1/.*

Your provided task isn't doing what you want because you're declaring that the directory should be absent, so it gets completely removed rather than emptied.

The command module won't work for the rm because it will not expand file globs, resulting in an error like:

rm: cannot remove '/home/location/dir1/*': No such file or directory
pirt
  • 1,153
  • 13
  • 21
  • I think there's some more Ansible-y ways to do this than just using the shell module. Lots of modules exist for file management in Ansible. – crock Jul 08 '22 at 22:26
0

You can try to use a command instead.

- name: Clean path
    command: rm -r /home/location/dir1/*
rvi
  • 13
  • 2
0

Why not remove the directory with the same task you're using, and re-add it immediately after using the same module? Seems like the most straightforward way to me. You could do some stuff with fileglob and with_items but that seems like over complicating a simple task.

- name: Remove folder
  file:
    state: absent
    path: "/home/location/dir1"

- name: Re-make folder
  file:
    state: directory
    path: "/home/location/dir1"
crock
  • 423
  • 3
  • 11
  • Many reasons why not. For one thing, your snippet doesn't capture the ownership and permissions of the directory and re-use them. – kmarsh May 10 '23 at 18:12