Ansible loop over list and dict

Viewed 30

I have a directory like this

/sample
|---iis
|    |---default
|    |     |-------testfile
|    |
|    |---lookup
|    |---README
|
|---linux
|
|---sql
|
|---win1
|    |---default
|    |     |------testfile
|    |
|    |---local
|    |
|    |---lookup
|    |     |------lookup.csv
|    |
|    |---README
|
---win2
|    |---default
|    |---local
|    |---lookup
|    |---README

I want to write an Ansible playbook to delete all contents within directories that begin with "win" except "local" directory. after running the playbook, sample directory must be something like this

/sample
|---iis
|    |---default
|    |     |-------testfile
|    |
|    |---lookup
|    |---README
|
|---linux
|
|---sql
|
|---win1
|    |---local
|
---win2
|    |---local

1 Answers

you could use this playbook:

- name: Find all directories win.*
  find:
    paths: files/sample
    patterns: win.*
    file_type: directory
    use_regex: yes
  register: folders_to_delete

  
- name: Find all subdirectories of win.* except local
  find:
    paths: "{{ item }}"
    exclude: local
    file_type: directory
  loop: "{{ folders_to_delete.files| map(attribute='path') }}"
  register: folderswin_to_delete

- name: delete all folders of win* except local
  file: 
    path: "{{ item.path}}"
    state: absent
  loop: "{{ folderswin_to_delete.results | map(attribute='files') | flatten }}"
Related