Equivalent of rm -Rf deleting subfolders

Since an approach like

- name: Delete all content (including directory)
  ansible.builtin.file:
    path: /home/guest/
	state: absent

is not feasible, you could take advantage of Developing modules and Create a custom module. Find a prototype here:

Custom Module library/rm_r.py

#!/usr/bin/python

from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

from ansible.module_utils.basic import AnsibleModule

import os, shutil

def run_module():
    module_args = dict(
        path=dict(type='str', required=True)
    )

    result = dict(
        changed=False,
        found_path=''
    )

    module = AnsibleModule(
        argument_spec=module_args,
        supports_check_mode=True
    )

    if module.check_mode:
        module.exit_json(**result)

    folder = module.params['path']

    # Main logic

    for f in os.listdir(folder):
        full_path = os.path.join(folder, f)
        if os.path.isfile(full_path) or os.path.islink(full_path):
            os.unlink(full_path)
        elif os.path.isdir(full_path):
            shutil.rmtree(full_path)
        result['found_path'] = result['found_path'] + full_path + '\n'
        result['changed'] = True

    module.exit_json(**result)

def main():
    run_module()

if __name__ == '__main__':
    main()

Playbook rm_r.yml

---
- hosts: localhost
  become: false
  gather_facts: false

  tasks:

  - name: Delete directory content
    rm_r:
      path: "/home/guest/foo/"
    register: result

  - debug:
      msg: "{{ result }}"

For a simple test

tree foo/
foo/
├── bar
├── one.tst
└── two.tst

it will result into an output of

TASK [debug] ************************
ok: [localhost] =>
  msg:
    changed: true
    failed: false
    found_path: |-
      /home/guest/foo/bar
      /home/guest/foo/one.tst
      /home/guest/foo/two.tst
	  
Delete directory content ----- 0.38s
debug ------------------------ 0.03s

deleted files and folder, and leave an empty directory

tree foo/
foo/

0 directories, 0 files

Just add error handling, enhance the behavior and perform further tests as necessary.

1 Like