From 51b56595986b6ea5ecc23ef85214a400a24eb64c Mon Sep 17 00:00:00 2001 From: David Shrewsbury Date: Thu, 13 May 2021 17:00:22 -0400 Subject: [PATCH] replace - better handling of file exceptions (#74686) --- changelogs/fragments/74686-replace-handle-file-exc.yml | 2 ++ lib/ansible/modules/replace.py | 10 +++++++--- 2 files changed, 9 insertions(+), 3 deletions(-) create mode 100644 changelogs/fragments/74686-replace-handle-file-exc.yml diff --git a/changelogs/fragments/74686-replace-handle-file-exc.yml b/changelogs/fragments/74686-replace-handle-file-exc.yml new file mode 100644 index 00000000000..8be2daed04f --- /dev/null +++ b/changelogs/fragments/74686-replace-handle-file-exc.yml @@ -0,0 +1,2 @@ +bugfixes: + - replace - better handling of file operation exceptions (https://github.com/ansible/ansible/pull/74686). diff --git a/lib/ansible/modules/replace.py b/lib/ansible/modules/replace.py index ed9fd1f2873..09600f61324 100644 --- a/lib/ansible/modules/replace.py +++ b/lib/ansible/modules/replace.py @@ -171,6 +171,7 @@ RETURN = r'''#''' import os import re import tempfile +from traceback import format_exc from ansible.module_utils._text import to_text, to_bytes from ansible.module_utils.basic import AnsibleModule @@ -242,9 +243,12 @@ def main(): if not os.path.exists(path): module.fail_json(rc=257, msg='Path %s does not exist !' % path) else: - f = open(path, 'rb') - contents = to_text(f.read(), errors='surrogate_or_strict', encoding=encoding) - f.close() + try: + with open(path, 'rb') as f: + contents = to_text(f.read(), errors='surrogate_or_strict', encoding=encoding) + except (OSError, IOError) as e: + module.fail_json(msg='Unable to read the contents of %s: %s' % (path, to_text(e)), + exception=format_exc()) pattern = u'' if params['after'] and params['before']: