Skip to content

Instantly share code, notes, and snippets.

@jgornick
Created May 19, 2015 12:49
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save jgornick/fcee337c2806b91b94d9 to your computer and use it in GitHub Desktop.
Save jgornick/fcee337c2806b91b94d9 to your computer and use it in GitHub Desktop.
Ansible: Remove All Files Except
---
- name: Capture files in path and register
shell: >
ls -1 /path/to/files
register: files
- name: Remove files except specified
file:
path: "/path/to/files/{{ item }}"
state: absent
with_items: files.stdout_lines
when: >
item not in list_of_files_to_keep
@andrewm41
Copy link

You need
with_items: "{{ files.stdout_lines }}"
on line 11

@larsnystrom
Copy link

Since this is the first result on Google, I thought I'd post a more modern approach (requires >= Ansible 2.5):

- name: Capture enabled sites to disable
  find:
    paths: /etc/apache2/sites-enabled
    file_type: link
    excludes: 
      - "mysite.conf"
      - "othersite.conf"
  register: sites_enabled

- name: Disable sites
  file:
    path: "{{ item.path }}"
    state: absent
  with_items: "{{ sites_enabled['files'] }}"

@EthanHemo
Copy link

Is there a way to make this more efficient?
I have a folder with multiple files and since it delete each file individually, it takes 3 minutes to delete everything where if i delete the whole folder it takes seconds.

@tveon
Copy link

tveon commented Jan 15, 2021

@AthanHemo https://docs.ansible.com/ansible/latest/collections/ansible/builtin/find_module.html
Without more context, it's hard to give a definitive answer - if you don't recurse into the directory, I'd think it would work. So either set recurse: no or depth: N depending on your concrete task.

@crapulent
Copy link

crapulent commented Apr 8, 2021

google gave me this gist while I was searching for solution for my problem (thanks!)

I think it can be little bit improved by adding

  changed_when: no
  check_mode: no

(so the first command will become

- name: Capture files in path and register
  shell: >
    ls -1 /etc/netplan/
  register: files
  changed_when: no
  check_mode: no

) so it can

  • not produce "CHANGED" event
  • run in check mode properly

@jgornick
Copy link
Author

Thank you all for the comments and suggestions! I've since been removed from working with ansible so thanks for the updates 😀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment