Ansible: How to delete files and folders inside a directory?

The code below deletes only the first file that it receives inside the web directory. I want to delete all files and folders inside the web directory and save the web directory. How can i do this?

- name: remove web dir contents file: path='/home/mydata/web/{{ item }}' state=absent with_fileglob: - /home/mydata/web/* 

Note: I tried rm -rf using the command and shell, but they do not work. Perhaps I am using them incorrectly.

Any help in the right direction would be appreciated.

I am using ansible 2.1.0.0

+135
delete-file delete-directory ansible ansible-playbook
Jul 05 '16 at 10:12
source share
18 answers

Below code will remove all artifact_path contents

 - name: Clean artifact path file: state: absent path: "{{ artifact_path }}/" 

Note : this will also delete the directory.

+127
Jul 05 '16 at 10:49
source share

Using the shell module (also idempotent ):

 - shell: /bin/rm -rf /home/mydata/web/* 

A clean solution if you are not interested in the creation date and owner / permission:

 - file: path=/home/mydata/web state=absent - file: path=/home/mydata/web state=directory 
+65
Jul 05 '16 at 10:54 on
source share

Delete the directory (basically this is a copy of https://stackoverflow.com/a/3/97985/ ... ), Ansible performs this operation with rmtree under the hood.

 - name: remove files and directories file: state: "{{ item }}" path: "/srv/deleteme/" owner: 1000 # set your owner, group, and mode accordingly group: 1000 mode: '0777' with_items: - absent - directory 



If you cannot delete the entire directory and create it again, you can scan it for files (and directories) and delete them one by one. Which will take some time. You probably want to make sure that you have [ssh_connection]\npipelining = True in your ansible.cfg.

 - block: - name: 'collect files' find: paths: "/srv/deleteme/" hidden: True recurse: True # file_type: any # Added in ansible 2.3 register: collected_files - name: 'collect directories' find: paths: "/srv/deleteme/" hidden: True recurse: True file_type: directory register: collected_directories - name: remove collected files and directories file: path: "{{ item.path }}" state: absent with_items: > {{ collected_files.files + collected_directories.files }} 
+47
Jan 24 '17 at 19:20
source share

try the command below, it should work

 - shell: ls -1 /some/dir register: contents - file: path=/some/dir/{{ item }} state=absent with_items: {{ contents.stdout_lines }} 
+18
Jul 05 '16 at 12:04 on
source share

I really didn't like the rm solution, also ansible gives you warnings about using rm. So, here's how to do it without the need to use rm and without warnings.

 - hosts: all tasks: - name: Ansible delete file glob find: paths: /etc/Ansible patterns: "*.txt" register: files_to_delete - name: Ansible remove file glob file: path: "{{ item.path }}" state: absent with_items: "{{ files_to_delete.files }}" 

source: http://www.mydailytutorials.com/ansible-delete-multiple-files-directories-ansible/

+17
Jul 31 '18 at 6:51
source share

A general rebuilt and fault tolerant implementation was created from all comments and suggestions:

 # collect stats about the dir - name: check directory exists stat: path: '{{ directory_path }}' register: dir_to_delete # delete directory if condition is true - name: purge {{directory_path}} file: state: absent path: '{{ directory_path }}' when: dir_to_delete.stat.exists and dir_to_delete.stat.isdir # create directory if deleted (or if it didn't exist at all) - name: create directory again file: state: directory path: '{{ directory_path }}' when: dir_to_delete is defined or dir_to_delete.stat.exist == False 
+4
Jun 28 '18 at 8:04
source share

Using the glob file will also work. There is a syntax error in the code you posted. I modified and tested this should work.

 - name: remove web dir contents file: path: "{{ item }}" state: absent with_fileglob: - "/home/mydata/web/*" 
+3
Jul 06 '16 at 9:14
source share

While Ansible is still discussing the implementation of state = empty https://github.com/ansible/ansible-modules-core/issues/902

 my_folder: "/home/mydata/web/" empty_path: "/tmp/empty" - name: "Create empty folder for wiping." file: path: "{{ empty_path }}" state: directory - name: "Wipe clean {{ my_folder }} with empty folder hack." synchronize: mode: push #note the backslash here src: "{{ empty_path }}/" dest: "{{ nl_code_path }}" recursive: yes delete: yes delegate_to: "{{ inventory_hostname }}" 

Please note that during synchronization you should be able to synchronize your files (with deletion) in any case.

+2
Oct. 10 '17 at 11:47 on
source share

In this regard, there is an open question .

At the moment, the solution works for me: create an empty folder locally and synchronize it with the remote one.

Here is an example book:

 - name: "Empty directory" hosts: * tasks: - name: "Create an empty directory (locally)" local_action: module: file state: directory path: "/tmp/empty" - name: Empty remote directory synchronize: src: /tmp/empty/ dest: /home/mydata/web/ delete: yes recursive: yes 
+1
Nov 14 '17 at 5:33
source share

I want to make sure that the find command only removes everything inside the directory and leaves the directory untouched, because in my case the directory is a file system. The system will give an error when trying to delete the file system, but this is not a good option. I use the shell option because this is the only working option I have found so far for this question.

What I've done:

Edit the hosts file by adding some variables:

 [all:vars] COGNOS_HOME=/tmp/cognos find=/bin/find 

And create a play:

 - hosts: all tasks: - name: Ansible remove files shell: "{{ find }} {{ COGNOS_HOME }} -xdev -mindepth 1 -delete" 

This will delete all files and directories in the directory / file system of the COGNOS_HOME variable. The "-mindepth 1" option ensures that the current directory is not affected.

0
Oct 09 '18 at 12:11
source share

I wrote a special module for cleaning files based on several filters, such as age, timestamp, globe templates, etc.

It is also compatible with older versions. It can be found here .

Here is an example:

 - cleanup_files: path_pattern: /tmp/*.log state: absent excludes: - foo* - bar* 
0
May 08 '19 at 22:35
source share

If you use Ansible> = 2.3, just a small template to copy and paste from ThorSummoners (the distinction between files and directories is no longer required).

 - name: Collect all fs items inside dir find: path: "{{ target_directory_path }}" hidden: true file_type: any changed_when: false register: collected_fsitems - name: Remove all fs items inside dir file: path: "{{ item.path }}" state: absent with_items: "{{ collected_fsitems.files }}" when: collected_fsitems.matched|int != 0 
0
May 22 '19 at 8:30
source share

Follow below:

 - hosts: all tasks: - name: Empty remote directory file: path: /home/felipe/files state: absent become: yes - name: Create file: path: /home/felipe/files state: directory owner: jboss group: jboss mode: u=rwx,g=rx,o=rx become: yes 
0
Jun 28 '19 at 21:58 on
source share

Here is what I came up with:

 - name: Get directory listing find: path: "{{ directory }}" file_type: any hidden: yes register: directory_content_result - name: Remove directory content file: path: "{{ item.path }}" state: absent with_items: "{{ directory_content_result.files }}" loop_control: label: "{{ item.path }}" 

First, we get a list of directories using find with the setting

  • file_type - any , so that we don’t miss nested directories and links
  • hidden - yes , so we do not skip hidden files
  • also do not set recurse to yes , as this is not only unnecessary, but may increase the execution time.

Then we look at this list using the file module. The output is a bit verbose, so loop_control.label will help us with limiting the output (our tip here ).




But I found that the previous solution was somewhat slow as it iterates over the contents, so I decided:

 - name: Get directory stats stat: path: "{{ directory }}" register: directory_stat - name: Delete directory file: path: "{{ directory }}" state: absent - name: Create directory file: path: "{{ directory }}" state: directory owner: "{{ directory_stat.stat.pw_name }}" group: "{{ directory_stat.stat.gr_name }}" mode: "{{ directory_stat.stat.mode }}" 
  • get directory properties using stat
  • delete directory
  • recreate a directory with the same properties.

That was enough for me, but you can also add attributes if you want.

0
Sep 22 '19 at 17:18
source share

Assuming you're always on Linux, try find cmd.

 - name: Clean everything inside {{ item }} shell: test -d {{ item }} && find {{ item }} -path '{{ item }}/*' -prune -exec rm -rf {} \; with_items: [/home/mydata/web] 

This should destroy the files / folders / hidden under /home/mydata/web

-one
Jan 25 '17 at 2:12 on
source share
T 删除 的 目录 , 然后 在 该 目录 目录 TTT
  - name: delete old data and clean cache file: path: "{{ item[0] }}" state: "{{ item[1] }}" with_nested: - [ "/data/server/{{ app_name }}/webapps/", "/data/server/{{ app_name }}/work/" ] - [ "absent", "directory" ] ignore_errors: yes 
-one
Aug 14 '18 at 15:01
source share

This is my example.

  1. Install repo
  2. Install rsyslog package
  3. stop rsyslog
  4. delete all files inside / var / log / rsyslog /
  5. start rsyslog

     - hosts: all tasks: - name: Install rsyslog-v8 yum repo template: src: files/rsyslog.repo dest: /etc/yum.repos.d/rsyslog.repo - name: Install rsyslog-v8 package yum: name: rsyslog state: latest - name: Stop rsyslog systemd: name: rsyslog state: stopped - name: cleann up /var/spool/rsyslog shell: /bin/rm -rf /var/spool/rsyslog/* - name: Start rsyslog systemd: name: rsyslog state: started 
-2
Aug 19 '19 at 2:14
source share

Below worked for me,

 - name: Ansible delete html directory file: path: /var/www/html state: directory 
-5
Sep 25 '17 at 12:33 on
source share



All Articles