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

**URL:** <https://forum.ansible.com/t/how-to-remove-temp-dir-even-in-case-of-an-error/24113>\
**Category:** Ansible Project\
**Created:** [March 31, 2017, 9:29am UTC](https://forum.ansible.com/t/how-to-remove-temp-dir-even-in-case-of-an-error/24113 "2017-03-31T09:29:35Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Cev\_Ing](https://avatars.discourse-cdn.com/v4/letter/c/f05b48/32.png) [@Cev\_Ing](https://forum.ansible.com/u/Cev_Ing)\
**Post date:** [March 31, 2017, 9:29am UTC](https://forum.ansible.com/t/how-to-remove-temp-dir-even-in-case-of-an-error/24113/1 "2017-03-31T09:29:35Z")

</div>

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?

```auto

```

---

<div class="post-metadata">

**Author:** ![Ricardo\_Carrillo\_Cru](https://avatars.discourse-cdn.com/v4/letter/r/87869e/32.png) [@Ricardo\_Carrillo\_Cru](https://forum.ansible.com/u/Ricardo_Carrillo_Cru)\
**Post date:** [March 31, 2017, 9:54am UTC](https://forum.ansible.com/t/how-to-remove-temp-dir-even-in-case-of-an-error/24113/2 "2017-03-31T09:54:56Z")

</div>

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

`
