authorized_key: Handle OSError raised

Handle OSError raised due to permission issue while
creating directory.

Fixes: ansible/ansible#34001

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
This commit is contained in:
Abhijeet Kasurde 2020-06-16 20:19:59 +05:30
parent 6a553ea4e8
commit 09c50c183f

View file

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