Repository: ansible/ansible

Issue:
Playbook directory missing from search path inside loops
<!---
Verify first that your issue/request is not already reported on GitHub.
THIS FORM WILL BE READ BY A MACHINE, COMPLETE ALL SECTIONS AS DESCRIBED.
Also test if the latest release, and devel branch are affected too.
ALWAYS add information AFTER (OUTSIDE) these html comments.
Otherwise it may end up being automatically closed by our bot. -->

##### SUMMARY
Normally, when executing tasks in a role, `ansible_search_path` includes the main playbook directory. However, when using loops, the playbook directory is missing from the search path.

##### ISSUE TYPE
 - Bug Report

##### COMPONENT NAME
<!--- Insert, BELOW THIS COMMENT, the name of the module, plugin, task or feature.
Do not include extra details here, e.g. "vyos_command" not "the network module vyos_command" or the full path-->
ansible_search_path

##### ANSIBLE VERSION
<!--- Paste, BELOW THIS COMMENT, verbatim output from "ansible --version" between quotes below -->
```
ansible 2.6.1
  config file = /Users/myself/my-playbook/ansible.cfg
  configured module search path = [u'/Users/myself/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /Library/Python/2.7/site-packages/ansible
  executable location = /usr/local/bin/ansible
  python version = 2.7.10 (default, Oct  6 2017, 22:29:07) [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)]
```

##### CONFIGURATION
<!--- If using Ansible 2.4 or above, paste, BELOW THIS COMMENT, the results of "ansible-config dump --only-changed"
Otherwise, mention any settings you have changed/added/removed in ansible.cfg
(or using the ANSIBLE_* environment variables).-->
```
DEFAULT_ROLES_PATH(/Users/myself/my-playbook/ansible.cfg) = [u'/Users/myself/my-playbook/roles']
```

##### OS / ENVIRONMENT
<!--- Mention, BELOW THIS COMMENT, the OS you are running Ansible from, and the OS you are
managing, or say "N/A" for anything that is not platform-specific.
Also mention the specific version of what you are trying to control,
e.g. if this is a network bug the version of firmware on the network device.-->
Reproduced on macOS 10.13.6 and Ubuntu 18.04.

##### STEPS TO REPRODUCE
<!--- For bugs, show exactly how to reproduce the problem, using a minimal test-case.
For new features, show how the feature would be used. -->

<!--- Paste example playbooks or commands between quotes below -->
`playbook.yml`:
```yaml
---
- hosts: "localhost"
  roles:
    - "search-path"
```

`roles/search-path/tasks/main.yml`:
```yaml
---
- debug:
    var: "ansible_search_path"

- debug:
    var: "item"
  loop:
    - "{{ ansible_search_path }}"
```


<!--- You can also paste gist.github.com links for larger files -->

##### EXPECTED RESULTS
<!--- What did you expect to happen when running the steps above? -->
Both the non-looped and looped tasks should print the same value of `ansible_search_path`.

##### ACTUAL RESULTS
<!--- What actually happened? If possible run with extra verbosity (-vvvv) -->

<!--- Paste verbatim command output between quotes below -->
```
PLAY [localhost] ***********************************************************************************************************************************************

TASK [Gathering Facts] *****************************************************************************************************************************************
ok: [localhost]

TASK [search-path : debug] *************************************************************************************************************************************
ok: [localhost] => {
    "ansible_search_path": [
        "/Users/myself/my-playbook/roles/search-path",
        "/Users/myself/my-playbook/roles/search-path/tasks",
        "/Users/myself/my-playbook"
    ]
}

TASK [search-path : debug] *************************************************************************************************************************************
ok: [localhost] => (item=[u'/Users/myself/my-playbook/roles/search-path', u'/Users/myself/my-playbook/roles/search-path/tasks']) => {
    "item": [
        "/Users/myself/my-playbook/roles/search-path",
        "/Users/myself/my-playbook/roles/search-path/tasks"
    ]
}

PLAY RECAP *****************************************************************************************************************************************************
localhost                  : ok=3    changed=0    unreachable=0    failed=0
```



Discussion:
Files identified in the description:
None

If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command.

[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)
<!--- boilerplate: components_banner --->

Resolving patch:
diff --git a/lib/ansible/executor/task_executor.py b/lib/ansible/executor/task_executor.py
--- a/lib/ansible/executor/task_executor.py
+++ b/lib/ansible/executor/task_executor.py
@@ -202,6 +202,10 @@ def _get_loop_items(self):
         # get search path for this task to pass to lookup plugins
         self._job_vars['ansible_search_path'] = self._task.get_search_path()
 
+        # ensure basedir is always in (dwim already searches here but we need to display it)
+        if self._loader.get_basedir() not in self._job_vars['ansible_search_path']:
+            self._job_vars['ansible_search_path'].append(self._loader.get_basedir())
+
         templar = Templar(loader=self._loader, shared_loader_obj=self._shared_loader_obj, variables=self._job_vars)
         items = None
         if self._task.loop_with:
@@ -253,10 +257,6 @@ def _get_loop_items(self):
                 if item is not None and not isinstance(item, UnsafeProxy):
                     items[idx] = UnsafeProxy(item)
 
-        # ensure basedir is always in (dwim already searches here but we need to display it)
-        if self._loader.get_basedir() not in self._job_vars['ansible_search_path']:
-            self._job_vars['ansible_search_path'].append(self._loader.get_basedir())
-
         return items
 
     def _run_loop(self, items):


Test patch:
diff --git a/test/integration/targets/loops/tasks/main.yml b/test/integration/targets/loops/tasks/main.yml
--- a/test/integration/targets/loops/tasks/main.yml
+++ b/test/integration/targets/loops/tasks/main.yml
@@ -223,3 +223,13 @@
 - assert:
     that:
       - with_list_passed_a_dict is failed
+
+- debug:
+    var: "item"
+  loop:
+    - "{{ ansible_search_path }}"
+  register: loop_search_path
+
+- assert:
+    that:
+      - ansible_search_path == loop_search_path.results.0.item