blockinfile: avoid crash on Python 3 when creating directory fails (#81662)

* Avoid crash on Python 3.

* Add a test for the crash on Python 3
pull/81586/head
Felix Fontein 2 years ago committed by GitHub
parent 3b608f97b1
commit 7f0baabbe0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -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)."

@ -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:

@ -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'"

@ -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

Loading…
Cancel
Save