From 8e664ad2269914123f16541e81c6bc16f4136ffe Mon Sep 17 00:00:00 2001
From: James Cammarata <jimi@sngx.net>
Date: Tue, 15 Sep 2015 13:08:54 -0400
Subject: [PATCH] Fix delegate_to localhost vs. 127.0.0.1 (and ::1)

---
 lib/ansible/executor/task_executor.py | 14 ++++++++++++--
 lib/ansible/playbook/conditional.py   |  4 ++--
 2 files changed, 14 insertions(+), 4 deletions(-)

diff --git a/lib/ansible/executor/task_executor.py b/lib/ansible/executor/task_executor.py
index 6780374e0d4..bf2f864a803 100644
--- a/lib/ansible/executor/task_executor.py
+++ b/lib/ansible/executor/task_executor.py
@@ -25,6 +25,7 @@ import subprocess
 import sys
 import time
 
+from jinja2.runtime import Undefined
 from six import iteritems
 
 from ansible import constants as C
@@ -511,7 +512,16 @@ class TaskExecutor:
         # get the vars for the delegate by its name
         try:
             self._display.debug("Delegating to %s" % self._task.delegate_to)
-            this_info = variables['hostvars'][self._task.delegate_to]
+            if self._task.delegate_to in C.LOCALHOST and self._task.delegate_to not in variables['hostvars']:
+                this_info = dict(ansible_connection="local")
+                for alt_local in C.LOCALHOST:
+                    if alt_local in variables['hostvars']:
+                        this_info = variables['hostvars'][self._task.delegate_to]
+                        if this_info == Undefined:
+                            this_info = dict(ansible_connection="local")
+                        break
+            else:
+                this_info = variables['hostvars'][self._task.delegate_to]
 
             # get the real ssh_address for the delegate and allow ansible_ssh_host to be templated
             self._play_context.remote_addr      = this_info.get('ansible_ssh_host', self._task.delegate_to)
@@ -528,7 +538,7 @@ class TaskExecutor:
         except Exception as e:
             # make sure the inject is empty for non-inventory hosts
             this_info = {}
-            self._display.debug("Delegate due to: %s" % str(e))
+            self._display.debug("Delegate to lookup failed due to: %s" % str(e))
 
         # Last chance to get private_key_file from global variables.
         # this is useful if delegated host is not defined in the inventory
diff --git a/lib/ansible/playbook/conditional.py b/lib/ansible/playbook/conditional.py
index a6e10c13dba..acfd54e8a06 100644
--- a/lib/ansible/playbook/conditional.py
+++ b/lib/ansible/playbook/conditional.py
@@ -60,8 +60,8 @@ class Conditional:
         # associated with it, so we pull it out now in case we need it for
         # error reporting below
         ds = None
-        if hasattr(self, 'get_ds'):
-            ds = self.get_ds()
+        if hasattr(self, '_ds'):
+            ds = getattr(self, '_ds')
 
         try:
             for conditional in self.when: