From 09c50c183f3f303613a089fc6e3077f79000078f Mon Sep 17 00:00:00 2001 From: Abhijeet Kasurde Date: Tue, 16 Jun 2020 20:19:59 +0530 Subject: [PATCH] authorized_key: Handle OSError raised Handle OSError raised due to permission issue while creating directory. Fixes: ansible/ansible#34001 Signed-off-by: Abhijeet Kasurde --- plugins/modules/authorized_key.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/plugins/modules/authorized_key.py b/plugins/modules/authorized_key.py index 005ba8f..d39f885 100644 --- a/plugins/modules/authorized_key.py +++ b/plugins/modules/authorized_key.py @@ -326,7 +326,10 @@ def keyfile(module, user, write=False, path=None, manage_dir=True, follow=False) if manage_dir: if not os.path.exists(sshdir): - os.mkdir(sshdir, int('0700', 8)) + try: + os.mkdir(sshdir, int('0700', 8)) + except OSError as e: + module.fail_json(msg="Failed to create directory %s : %s" % (sshdir, to_native(e))) if module.selinux_enabled(): module.set_default_selinux_context(sshdir, False) os.chown(sshdir, uid, gid) @@ -462,15 +465,14 @@ def parsekeys(module, lines): def writefile(module, filename, content): - - fd, tmp_path = tempfile.mkstemp('', 'tmp', os.path.dirname(filename)) - f = open(tmp_path, "w") + dummy, tmp_path = tempfile.mkstemp() try: - f.write(content) + with open(tmp_path, "w") as f: + f.write(content) except IOError as e: + module.add_cleanup_file(tmp_path) module.fail_json(msg="Failed to write to file %s: %s" % (tmp_path, to_native(e))) - f.close() module.atomic_move(tmp_path, filename)