diff options
author | Sam Doran <sdoran@redhat.com> | 2019-06-28 16:19:27 -0400 |
---|---|---|
committer | GitHub <noreply@github.com> | 2019-06-28 16:19:27 -0400 |
commit | 6cf6f5a34bebe01f96782a171db8d83d4e7828ca (patch) | |
tree | 90eb9cb093c52d067bab0846ab91a4735d5fe253 /lib/ansible/utils | |
parent | 875e7c3e5036b1410e4170c4ff2589c3f12e5ac7 (diff) | |
download | ansible-6cf6f5a34bebe01f96782a171db8d83d4e7828ca.tar.gz |
Use atexit to cleanup tmp dirs (#56532)
* Wrap everything in try/except to avoid leaving files behind
* Add unit tests, integration tests, and changelog
* Do text the correct way
Diffstat (limited to 'lib/ansible/utils')
-rw-r--r-- | lib/ansible/utils/path.py | 27 |
1 files changed, 27 insertions, 0 deletions
diff --git a/lib/ansible/utils/path.py b/lib/ansible/utils/path.py index 37dd4c9139..4fd416c280 100644 --- a/lib/ansible/utils/path.py +++ b/lib/ansible/utils/path.py @@ -18,6 +18,7 @@ from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os +import shutil from errno import EEXIST from ansible.errors import AnsibleError @@ -103,3 +104,29 @@ def basedir(source): dname = os.path.abspath(dname) return to_text(dname, errors='surrogate_or_strict') + + +def cleanup_tmp_file(path, warn=False): + """ + Removes temporary file or directory. Optionally display a warning if unable + to remove the file or directory. + + :arg path: Path to file or directory to be removed + :kwarg warn: Whether or not to display a warning when the file or directory + cannot be removed + """ + try: + if os.path.exists(path): + try: + if os.path.isdir(path): + shutil.rmtree(path) + elif os.path.isfile(path): + os.unlink(path) + except Exception as e: + if warn: + # Importing here to avoid circular import + from ansible.utils.display import Display + display = Display() + display.display(u'Unable to remove temporary file {0}'.format(to_text(e))) + except Exception: + pass |