From b698f7a44b1480fa857656fdc5b69ce49d306be0 Mon Sep 17 00:00:00 2001 From: James Cammarata Date: Sun, 30 Mar 2014 01:34:33 -0500 Subject: [PATCH] Add option to create host_key directory if it doesn't exist Fixes #6731 --- lib/ansible/module_utils/known_hosts.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/lib/ansible/module_utils/known_hosts.py b/lib/ansible/module_utils/known_hosts.py index 68ef2828319..62600d7b4da 100644 --- a/lib/ansible/module_utils/known_hosts.py +++ b/lib/ansible/module_utils/known_hosts.py @@ -30,7 +30,7 @@ import hmac from hashlib import sha1 HASHED_KEY_MAGIC = "|1|" -def add_git_host_key(module, url, accept_hostkey=True): +def add_git_host_key(module, url, accept_hostkey=True, create_dir=True): """ idempotently add a git url hostkey """ @@ -40,7 +40,7 @@ def add_git_host_key(module, url, accept_hostkey=True): known_host = check_hostkey(module, fqdn) if not known_host: if accept_hostkey: - rc, out, err = add_host_key(module, fqdn) + rc, out, err = add_host_key(module, fqdn, create_dir=create_dir) if rc != 0: module.fail_json(msg="failed to add %s hostkey: %s" % (fqdn, out + err)) else: @@ -120,7 +120,7 @@ def not_in_host_file(self, host): return True -def add_host_key(module, fqdn, key_type="rsa"): +def add_host_key(module, fqdn, key_type="rsa", create_dir=False): """ use ssh-keyscan to add the hostkey """ @@ -136,7 +136,15 @@ def add_host_key(module, fqdn, key_type="rsa"): user_ssh_dir = os.path.expanduser(user_ssh_dir) if not os.path.exists(user_ssh_dir): - module.fail_json(msg="%s does not exist" % user_ssh_dir) + if create_dir: + try: + os.makedirs(user_ssh_dir, 0700) + except: + module.fail_json(msg="failed to create host key directory: %s" % user_ssh_dir) + else: + module.fail_json(msg="%s does not exist" % user_ssh_dir) + elif not os.path.isdir(user_ssh_dir): + module.fail_json(msg="%s is not a directory" % user_ssh_dir) this_cmd = "%s -t %s %s" % (keyscan_cmd, key_type, fqdn)