From b2e94e53fc372cb131272458104f9963124a3a4c Mon Sep 17 00:00:00 2001 From: Stephen Fromm Date: Fri, 19 Oct 2012 22:54:08 -0700 Subject: [PATCH] Write keys file to temp location to avoid potential corruption --- library/authorized_key | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/library/authorized_key b/library/authorized_key index aa97b6c900..d75aa96f52 100755 --- a/library/authorized_key +++ b/library/authorized_key @@ -68,6 +68,8 @@ import sys import os import pwd import os.path +import tempfile +import shutil def keyfile(user, write=False): """ @@ -114,11 +116,16 @@ def readkeys(filename): f.close() return keys -def writekeys( filename, keys): +def writekeys(module, filename, keys): - f = open(filename,"w") - f.writelines( (key + "\n" for key in keys) ) + fd, tmp_path = tempfile.mkstemp() + f = open(tmp_path,"w") + try: + f.writelines( (key + "\n" for key in keys) ) + except IOError, e: + module.fail_json(msg="Failed to write to file %s: %s" % (tmp_path, str(e))) f.close() + shutil.move(tmp_path, filename) def enforce_state(module, params): """ @@ -139,13 +146,13 @@ def enforce_state(module, params): if present: module.exit_json(changed=False) keys.append(key) - writekeys(keyfile(user,write=True), keys) + writekeys(module, keyfile(user,write=True), keys) elif state=="absent": if not present: module.exit_json(changed=False) keys.remove(key) - writekeys(keyfile(user,write=True), keys) + writekeys(module, keyfile(user,write=True), keys) params['changed'] = True return params