diff --git a/changelogs/fragments/81662-blockinfile-exc.yml b/changelogs/fragments/81662-blockinfile-exc.yml new file mode 100644 index 00000000000..c505ba1923d --- /dev/null +++ b/changelogs/fragments/81662-blockinfile-exc.yml @@ -0,0 +1,2 @@ +bugfixes: + - "blockinfile - avoid crash with Python 3 if creating the directory fails when ``create=true`` (https://github.com/ansible/ansible/pull/81662)." diff --git a/lib/ansible/modules/blockinfile.py b/lib/ansible/modules/blockinfile.py index a44285197a5..8c83bf0bdd9 100644 --- a/lib/ansible/modules/blockinfile.py +++ b/lib/ansible/modules/blockinfile.py @@ -272,8 +272,10 @@ def main(): if not os.path.exists(destpath) and not module.check_mode: try: os.makedirs(destpath) + except OSError as e: + module.fail_json(msg='Error creating %s Error code: %s Error description: %s' % (destpath, e.errno, e.strerror)) except Exception as e: - module.fail_json(msg='Error creating %s Error code: %s Error description: %s' % (destpath, e[0], e[1])) + module.fail_json(msg='Error creating %s Error: %s' % (destpath, to_native(e))) original = None lines = [] else: diff --git a/test/integration/targets/blockinfile/tasks/create_dir.yml b/test/integration/targets/blockinfile/tasks/create_dir.yml new file mode 100644 index 00000000000..a16ada5e49a --- /dev/null +++ b/test/integration/targets/blockinfile/tasks/create_dir.yml @@ -0,0 +1,29 @@ +- name: Set up a directory to test module error handling + file: + path: "{{ remote_tmp_dir_test }}/unreadable" + state: directory + mode: "000" + +- name: Create a directory and file with blockinfile + blockinfile: + path: "{{ remote_tmp_dir_test }}/unreadable/createme/file.txt" + block: | + line 1 + line 2 + state: present + create: yes + register: permissions_error + ignore_errors: yes + +- name: assert the error looks right + assert: + that: + - permissions_error.msg.startswith('Error creating') + when: "ansible_user_id != 'root'" + +- name: otherwise (root) assert the directory and file exists + stat: + path: "{{ remote_tmp_dir_test }}/unreadable/createme/file.txt" + register: path_created + failed_when: path_created.exists is false + when: "ansible_user_id == 'root'" diff --git a/test/integration/targets/blockinfile/tasks/main.yml b/test/integration/targets/blockinfile/tasks/main.yml index b7f5161c8a5..f26cb165e9c 100644 --- a/test/integration/targets/blockinfile/tasks/main.yml +++ b/test/integration/targets/blockinfile/tasks/main.yml @@ -31,6 +31,7 @@ - import_tasks: add_block_to_existing_file.yml - import_tasks: create_file.yml +- import_tasks: create_dir.yml - import_tasks: preserve_line_endings.yml - import_tasks: block_without_trailing_newline.yml - import_tasks: file_without_trailing_newline.yml