How to remove temp dir even in case of an error?

In Bash I use mktemp together with trap to always remove the temp dir.

When I use the tempfile module, how do I remove the tempfile, in case of an error, which terminates the playbook run?


You could register the output of tempfile in a variable and use the block rescue feature.

Something like:

`

connection: local

tasks:

  • block:
  • tempfile:
    state: directory
    register: tempfile_out
  • command: /bin/false
    rescue:
  • debug: msg=“Yikes, something broke, cleaning up tmp dir {{ tempfile_out.path }}”
  • file:
    name: “{{ tempfile_out.path }}”
    state: absent

`