From 30cf73e83a7a9d13faf88f5527581c11f605f317 Mon Sep 17 00:00:00 2001
From: Matthew Vernon <mcv21@cam.ac.uk>
Date: Tue, 31 Mar 2015 17:19:11 +0100
Subject: [PATCH] Fix for issue #353 (handle change in ssh-keygen behaviour)

Prior to openssh 6.4, ssh-keygen -F returned 0 (and no output) when no
host was found. After then, it instead returned 1 and no output. This
revised code behaves correctly with either behaviour. There is
currently no other code path that results in exit(1) and no output.
---
 system/known_hosts.py | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)

diff --git a/system/known_hosts.py b/system/known_hosts.py
index 893eca3dcb7..c2030758cc8 100644
--- a/system/known_hosts.py
+++ b/system/known_hosts.py
@@ -188,10 +188,14 @@ def search_for_host_key(module,host,key,path,sshkeygen):
     replace=False
     if os.path.exists(path)==False:
         return False, False
+    #openssh >=6.4 has changed ssh-keygen behaviour such that it returns
+    #1 if no host is found, whereas previously it returned 0
     rc,stdout,stderr=module.run_command([sshkeygen,'-F',host,'-f',path],
-                                 check_rc=True)
-    if stdout=='': #host not found
-        return False, False
+                                 check_rc=False)
+    if stdout=='' and stderr=='' and (rc==0 or rc==1):
+        return False, False #host not found, no other errors
+    if rc!=0: #something went wrong
+        module.fail_json(msg="ssh-keygen failed (rc=%d,stdout='%s',stderr='%s')" % (rc,stdout,stderr))
 
 #If user supplied no key, we don't want to try and replace anything with it
     if key is None: