Repository: ansible/ansible

Issue:
fatal errors are sent to stdout instead of stderr
<!---
Please do not report issues/requests related to Ansible modules here !!

Report them to the appropriate modules-core or modules-extras project:
  - https://github.com/ansible/ansible-modules-core/issues
  - https://github.com/ansible/ansible-modules-extras/issues

Also verify first that your issue/request is not already reported in GitHub
-->
##### ISSUE TYPE

<!--- Pick one below and delete the rest: -->
- Bug Report
##### COMPONENT NAME

<!--- Name of the plugin/task/feature -->
##### ANSIBLE VERSION

<!--- Paste verbatim output from “ansible --version” between quotes below -->

```
ansible 2.0.2.0
  config file = /etc/ansible/ansible.cfg
  configured module search path = Default w/o overrides
```
##### CONFIGURATION

<!---
Mention any settings you have changed/added/removed in ansible.cfg
(or using the ANSIBLE_* environment variables).
-->
##### OS / ENVIRONMENT

<!---
Mention the OS you are running Ansible from, and the OS you are
managing, or say “N/A” for anything that is not platform-specific.
-->
##### SUMMARY

<!--- Explain the problem briefly -->

Ansible reporting output sends fatal errors to stdout instead of stderr.
##### STEPS TO REPRODUCE

<!---
For bugs, show exactly how to reproduce the problem.
For new features, show how the feature would be used.
-->

Just run a playbook or a command for which you expect a fatal error (e.g. host is down) and redirect stderr to a file. The error output will be visible on the console, but the file will be empty.

<!--- Paste example playbooks or commands between quotes below -->

```
~# ansible unreachablehost.example.com -m command -a 'uptime' 2>errout
unreachablehost.example.com | UNREACHABLE! => {
    "changed": false, 
    "msg": "Failed to connect to the host via ssh.", 
    "unreachable": true
}
~# cat errout
~#
```

<!--- You can also paste gist.github.com links for larger files -->
##### EXPECTED RESULTS

<!--- What did you expect to happen when running the steps above? -->

I expected no output on the console and the file `errout` to contain the output instead.
##### ACTUAL RESULTS

<!--- What actually happened? If possible run with extra verbosity (-vvvv) -->

Errors were output to the console and the `errout` file was empty

<!--- Paste verbatim command output between quotes below -->

```

```



Discussion:
That's because whole class is missing.
fatal errors are redirected to stderr with class CallbackModule.
connection errors are handled by class ConnectionError.
which is mentioned only once and has 2 lines ( one of wich is 'pass' ).
I'd gladly help you if I knew how ansible coders want this class writen.

As discussed in the linked PR, this is not a mistake, ansible-playbook did not get an error, it is reporting the status of tasks on hosts (all to stdout). 

If ansible-playbook itself suffers an error it will output to stderr, but it will not do so for reporting the steps of a playbook. This is the expected default behavior, the callback plugin system allows you to modify this behavior if you are so inclined, that is what I asked the submitter to do.

As such,I'm closing this issue as it is not a bug.


Resolving patch:
diff --git a/lib/ansible/plugins/callback/stderr.py b/lib/ansible/plugins/callback/stderr.py
new file mode 100644
--- /dev/null
+++ b/lib/ansible/plugins/callback/stderr.py
@@ -0,0 +1,80 @@
+# (c) 2017, Frederic Van Espen <github@freh.be>
+#
+# This file is part of Ansible
+#
+# Ansible is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# Ansible is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.
+
+# Make coding more python3-ish
+from __future__ import (absolute_import, division, print_function)
+__metaclass__ = type
+
+from ansible import constants as C
+from ansible.plugins.callback.default import CallbackModule as CallbackModule_default
+
+
+class CallbackModule(CallbackModule_default):
+
+    '''
+    This is the stderr callback plugin, which reuses the default
+    callback plugin but sends error output to stderr.
+    '''
+
+    CALLBACK_VERSION = 2.0
+    CALLBACK_TYPE = 'stdout'
+    CALLBACK_NAME = 'stderr'
+
+    def __init__(self):
+
+        self.super_ref = super(CallbackModule, self)
+        self.super_ref.__init__()
+
+    def v2_runner_on_failed(self, result, ignore_errors=False):
+
+        delegated_vars = result._result.get('_ansible_delegated_vars', None)
+        self._clean_results(result._result, result._task.action)
+
+        if self._play.strategy == 'free' and self._last_task_banner != result._task._uuid:
+            self._print_task_banner(result._task)
+
+        self._handle_exception(result._result, errors_to_stderr=True)
+        self._handle_warnings(result._result)
+
+        if result._task.loop and 'results' in result._result:
+            self._process_items(result)
+
+        else:
+            if delegated_vars:
+                self._display.display("fatal: [%s -> %s]: FAILED! => %s" % (result._host.get_name(), delegated_vars['ansible_host'],
+                                                                            self._dump_results(result._result)), color=C.COLOR_ERROR,
+                                      stderr=True)
+            else:
+                self._display.display("fatal: [%s]: FAILED! => %s" % (result._host.get_name(), self._dump_results(result._result)),
+                                      color=C.COLOR_ERROR, stderr=True)
+
+        if ignore_errors:
+            self._display.display("...ignoring", color=C.COLOR_SKIP)
+
+    def _handle_exception(self, result, errors_to_stderr=False):
+
+        if 'exception' in result:
+            msg = "An exception occurred during task execution. "
+            if self._display.verbosity < 3:
+                # extract just the actual error message from the exception text
+                error = result['exception'].strip().split('\n')[-1]
+                msg += "To see the full traceback, use -vvv. The error was: %s" % error
+            else:
+                msg = "The full traceback is:\n" + result['exception']
+                del result['exception']
+
+            self._display.display(msg, color=C.COLOR_ERROR, stderr=errors_to_stderr)


Test patch: