Using Ansible, I need to ensure, all of the subfolders of a certain directory do not exist except for a few, that must be retained.
The list to be kept will be specified externally -- say, as subfolders_to_keep.
The only way I can see is to first use the find-module to enumerate the subdirectories, and then, using file, delete all, that aren't exceptional -- in a loop.
That would be a fairly long loop here — of the 50-plus entries, only 4 are to survive. Perhaps, there is a more elegant way?
Right, with significant performance effects. See in example Ansible: How to optimize running speed of a playbook? or How do I optimize performance of Ansible playbook?
Since there is no out-of-box module available for such kind of tasks, in your specific Use Case
shellmodule – Execute shell commands on targets withfindorrmtogether with excludes. See in examplefindscriptmodule – Runs a local script on a remote node after transferring it. Maybe read before about How to execute ashellscript on a Remote Server using Ansible?.library/pygrep.py. Shell or Bash is also possible but probably more complex. An example can be found under Example Modulebetween.sh.