Repository: ansible/ansible

Issue:
no_log: true hides localhost delegation
<!---
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
<!--- Explain the problem briefly -->

When using a task with `delegate_to: localhost` and `no_log: true`, the log output does not indicate a local action is performed. Instead of
```
ok: [127.0.0.1 -> localhost]
```
```
ok: [127.0.0.1]
```
Which seems to indicate no delegation happened. In my real program, I used other hosts then 127.0.0.1 but the issue is the same

##### 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 VERSION
<!--- Paste, BELOW THIS COMMENT, verbatim output from "ansible --version" between quotes below -->
```
ansible 2.6.0
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/local/lib/python2.7/dist-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.7.12 (default, Nov 19 2016, 06:48:10) [GCC 5.4.0 20160609]
```

##### 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).-->

##### 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.-->
N/A

##### 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 -->
```yaml
---
- hosts: all
  gather_facts: false
  tasks:
   - uri:
       url: "http://google.com"
     delegate_to: localhost
     no_log: true
   - uri:
       url: "http://google.com"
     delegate_to: localhost
   - debug:
       msg: "foo"
     delegate_to: localhost
     no_log: true
   - debug:
       msg: "foo"
     delegate_to: localhost
~

Inventory: 
[foo-servers]
127.0.0.1

```

<!--- You can also paste gist.github.com links for larger files -->

##### EXPECTED RESULTS
<!--- What did you expect to happen when running the steps above? -->
```
ok: [127.0.0.1 -> localhost]
```
should be printed for every of these command. 
According to the log, the delegation is correctly performed but the log is not indicating this.

##### ACTUAL RESULTS
<!--- What actually happened? If possible run with extra verbosity (-vvvv) -->



<!--- Paste verbatim command output between quotes below -->
```
ansible-playbook 2.6.0
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/local/lib/python2.7/dist-packages/ansible
  executable location = /usr/bin/ansible-playbook
  python version = 2.7.12 (default, Nov 19 2016, 06:48:10) [GCC 5.4.0 20160609]
Using /etc/ansible/ansible.cfg as config file
Parsed /root/int inventory source with ini plugin

PLAYBOOK: la.yml *****************************************************************************************************************************************
1 plays in la.yml

PLAY [all] ***********************************************************************************************************************************************
META: ran handlers

TASK [uri] ***********************************************************************************************************************************************
task path: /root/la.yml:5
<localhost> ESTABLISH LOCAL CONNECTION FOR USER: root
<localhost> EXEC /bin/sh -c 'echo ~root && sleep 0'
<localhost> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /root/.ansible/tmp/ansible-tmp-1530781265.73-183065552218219 `" && echo ansible-tmp-1530781265.73-183065552218219="` echo /root/.ansible/tmp/ansible-tmp-1530781265.73-183065552218219 `" ) && sleep 0'
Using module file /usr/local/lib/python2.7/dist-packages/ansible/modules/net_tools/basics/uri.py
<localhost> PUT /root/.ansible/tmp/ansible-local-1807IBel0k/tmpYpR5Hg TO /root/.ansible/tmp/ansible-tmp-1530781265.73-183065552218219/uri.py
<localhost> EXEC /bin/sh -c 'chmod u+x /root/.ansible/tmp/ansible-tmp-1530781265.73-183065552218219/ /root/.ansible/tmp/ansible-tmp-1530781265.73-183065552218219/uri.py && sleep 0'
<localhost> EXEC /bin/sh -c '/usr/bin/python /root/.ansible/tmp/ansible-tmp-1530781265.73-183065552218219/uri.py && sleep 0'
<localhost> EXEC /bin/sh -c 'rm -f -r /root/.ansible/tmp/ansible-tmp-1530781265.73-183065552218219/ > /dev/null 2>&1 && sleep 0'
ok: [127.0.0.1] => {
    "censored": "the output has been hidden due to the fact that 'no_log: true' was specified for this result", 
    "changed": false
}

TASK [uri] ***********************************************************************************************************************************************
task path: /root/la.yml:9
<localhost> ESTABLISH LOCAL CONNECTION FOR USER: root
<localhost> EXEC /bin/sh -c 'echo ~root && sleep 0'
<localhost> EXEC /bin/sh -c '( umask 77 && mkdir -p "` echo /root/.ansible/tmp/ansible-tmp-1530781266.32-55153762030353 `" && echo ansible-tmp-1530781266.32-55153762030353="` echo /root/.ansible/tmp/ansible-tmp-1530781266.32-55153762030353 `" ) && sleep 0'
Using module file /usr/local/lib/python2.7/dist-packages/ansible/modules/net_tools/basics/uri.py
<localhost> PUT /root/.ansible/tmp/ansible-local-1807IBel0k/tmpAiAM9f TO /root/.ansible/tmp/ansible-tmp-1530781266.32-55153762030353/uri.py
<localhost> EXEC /bin/sh -c 'chmod u+x /root/.ansible/tmp/ansible-tmp-1530781266.32-55153762030353/ /root/.ansible/tmp/ansible-tmp-1530781266.32-55153762030353/uri.py && sleep 0'
<localhost> EXEC /bin/sh -c '/usr/bin/python /root/.ansible/tmp/ansible-tmp-1530781266.32-55153762030353/uri.py && sleep 0'
<localhost> EXEC /bin/sh -c 'rm -f -r /root/.ansible/tmp/ansible-tmp-1530781266.32-55153762030353/ > /dev/null 2>&1 && sleep 0'
ok: [127.0.0.1 -> localhost] => {
    "accept_ranges": "none", 
    "cache_control": "private, max-age=0", 
    "changed": false, 
    "connection": "close", 
    "content_type": "text/html; charset=ISO-8859-1", 
    "cookies": {
        "1P_JAR": "2018-07-05-09", 
        "NID": "133=hBIG12zrdnVAYrlnkwZBgH1rqaZhQRZc_GJC5spPsvvtA_DFhqi-hTSL2ZZt1P3FhpVLeFpkwYJfe0Tt7sqYIJXYhK47wGmqckHcaq7Wal2vFEIf2cdlWp3KTsYMaXrD"
    }, 
    "cookies_string": "1P_JAR=2018-07-05-09; NID=133=hBIG12zrdnVAYrlnkwZBgH1rqaZhQRZc_GJC5spPsvvtA_DFhqi-hTSL2ZZt1P3FhpVLeFpkwYJfe0Tt7sqYIJXYhK47wGmqckHcaq7Wal2vFEIf2cdlWp3KTsYMaXrD", 
    "date": "Thu, 05 Jul 2018 09:01:06 GMT", 
    "expires": "-1", 
    "invocation": {
        "module_args": {
            "attributes": null, 
            "backup": null, 
            "body": null, 
            "body_format": "raw", 
            "client_cert": null, 
            "client_key": null, 
            "content": null, 
            "creates": null, 
            "delimiter": null, 
            "dest": null, 
            "directory_mode": null, 
            "follow": false, 
            "follow_redirects": "safe", 
            "force": false, 
            "force_basic_auth": false, 
            "group": null, 
            "headers": {}, 
            "http_agent": "ansible-httpget", 
            "method": "GET", 
            "mode": null, 
            "owner": null, 
            "regexp": null, 
            "remote_src": null, 
            "removes": null, 
            "return_content": false, 
            "selevel": null, 
            "serole": null, 
            "setype": null, 
            "seuser": null, 
            "src": null, 
            "status_code": [
                200
            ], 
            "timeout": 30, 
            "unsafe_writes": null, 
            "url": "http://google.com", 
            "url_password": null, 
            "url_username": null, 
            "use_proxy": true, 
            "validate_certs": true
        }
    }, 
    "msg": "OK (unknown bytes)", 
    "p3p": "CP=\"This is not a P3P policy! See g.co/p3phelp for more info.\"", 
    "redirected": true, 
    "server": "gws", 
    "set_cookie": "1P_JAR=2018-07-05-09; expires=Sat, 04-Aug-2018 09:01:06 GMT; path=/; domain=.google.com, NID=133=hBIG12zrdnVAYrlnkwZBgH1rqaZhQRZc_GJC5spPsvvtA_DFhqi-hTSL2ZZt1P3FhpVLeFpkwYJfe0Tt7sqYIJXYhK47wGmqckHcaq7Wal2vFEIf2cdlWp3KTsYMaXrD; expires=Fri, 04-Jan-2019 09:01:06 GMT; path=/; domain=.google.com; HttpOnly", 
    "status": 200, 
    "url": "http://www.google.com/", 
    "vary": "Accept-Encoding", 
    "x_frame_options": "SAMEORIGIN", 
    "x_xss_protection": "1; mode=block"
}

TASK [debug] *********************************************************************************************************************************************
task path: /root/la.yml:12
ok: [127.0.0.1] => {
    "censored": "the output has been hidden due to the fact that 'no_log: true' was specified for this result"
}

TASK [debug] *********************************************************************************************************************************************
task path: /root/la.yml:16
ok: [127.0.0.1 -> localhost] => {
    "msg": "foo"
}
META: ran handlers
META: ran handlers

PLAY RECAP ***********************************************************************************************************************************************
127.0.0.1                  : ok=4    changed=0    unreachable=0    failed=0   
 

```



Discussion:

Resolving patch:
diff --git a/lib/ansible/executor/task_result.py b/lib/ansible/executor/task_result.py
--- a/lib/ansible/executor/task_result.py
+++ b/lib/ansible/executor/task_result.py
@@ -12,6 +12,7 @@
 
 _IGNORE = ('failed', 'skipped')
 _PRESERVE = ('attempts', 'changed', 'retries')
+_SUB_PRESERVE = {'_ansible_delegated_vars': ('ansible_host', 'ansible_port', 'ansible_user', 'ansible_connection')}
 
 
 class TaskResult:
@@ -112,9 +113,19 @@ def clean_copy(self):
 
         if self._task.no_log or self._result.get('_ansible_no_log', False):
             x = {"censored": "the output has been hidden due to the fact that 'no_log: true' was specified for this result"}
+
+            # preserve full
             for preserve in _PRESERVE:
                 if preserve in self._result:
                     x[preserve] = self._result[preserve]
+
+            # preserve subset
+            for sub in _SUB_PRESERVE:
+                if sub in self._result:
+                    x[sub] = {}
+                    for key in _SUB_PRESERVE[sub]:
+                        x[sub][key] = self._result[sub][key]
+
             result._result = x
         elif self._result:
             result._result = deepcopy(self._result)


Test patch: