# Buggy code
def _handle_error(
    remaining_retries, command, return_tuple, no_log, host, display=display
):
    # sshpass errors
    if command == b"sshpass":
        # Error 5 is invalid/incorrect password. Raise an exception to prevent retries from locking the account.
        if return_tuple[0] == 5:
            msg = "Invalid/incorrect username/password. Skipping remaining {0} retries to prevent account lockout:".format(
                remaining_retries
            )
            if remaining_retries <= 0:
                msg = "Invalid/incorrect password:"
            if no_log:
                msg = "{0} <error censored due to no log>".format(msg)
            else:
                msg = "{0} {1}".format(msg, to_native(return_tuple[2].rstrip()))
            raise AnsibleAuthenticationFailure(msg)

        # sshpass returns codes are 1-6. We handle 5 previously, so this catches other scenarios.
        # No exception is raised, so the connection is retried.
        elif return_tuple[0] in [1, 2, 3, 4, 6]:
            msg = "sshpass error:"
            if no_log:
                msg = "{0} <error censored due to no log>".format(msg)
            else:
                msg = "{0} {1}".format(msg, to_native(return_tuple[2].rstrip()))

    if return_tuple[0] == 255:
        SSH_ERROR = True
        for signature in b_NOT_SSH_ERRORS:
            if signature in return_tuple[1]:
                SSH_ERROR = False
                break

        if SSH_ERROR:
            msg = "Failed to connect to the host via ssh:"
            if no_log:
                msg = "{0} <error censored due to no log>".format(msg)
            else:
                msg = "{0} {1}".format(msg, to_native(return_tuple[2]).rstrip())
            raise AnsibleConnectionFailure(msg)

    # For other errors, no execption is raised so the connection is retried and we only log the messages
    if 1 <= return_tuple[0] <= 254:
        msg = "Failed to connect to the host via ssh:"
        if no_log:
            msg = "{0} <error censored due to no log>".format(msg)
        else:
            msg = "{0} {1}".format(msg, to_native(return_tuple[2]).rstrip())
        display.vvv(msg, host=host)


# Traceback (UnicodeDecodeError)
TASK [stat] *************************************************************************************************************************************************************
task path: /home/jenkins/playbook.yml:3
Friday 14 June 2019  10:36:17 +0200 (0:00:00.170)       0:00:00.170 ***********
Using module file /jenkins/test/ansible/lib/python2.6/site-packages/ansible/modules/files/stat.py
<server> ESTABLISH SSH CONNECTION FOR USER: myuser
<server> SSH: EXEC ssh -o PreferredAuthentications=publickey -o StrictHostKeyChecking=no -o Port=22 -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=myuser -o ConnectTimeout=20 server '/bin/sh -c '"'"'/usr/bin/python &amp;&amp; sleep 0'"'"''
<server> (1, '\n{"msg": "Permission denied", "failed": true, "exception": "  File \\"/tmp/ansible_Vvkdbf/ansible_module_stat.py\\", line 476, in main\\n    st = os.lstat(b_path)\\n", "invocation": {"module_args": {"checksum_algorithm": "sha1", "get_checksum": true, "follow": false, "path": "/home/anotheruser/lvi", "get_md5": null, "get_mime": true, "get_attributes": true}}}\n', "ATTENTION:\nQuiconque acc\xc3\xa9derait ou tenterait d'acc\xc3\xa9der \xc3\xa0 ce syst\xc3\xa8me.\n\n")
The full traceback is:
Traceback (most recent call last):
File "/jenkins/test/ansible/lib/python2.6/site-packages/ansible/executor/task_executor.py", line 139, in run
res = self._execute()
File "/jenkins/test/ansible/lib/python2.6/site-packages/ansible/executor/task_executor.py", line 584, in _execute
result = self._handler.run(task_vars=variables)
File "/jenkins/test/ansible/lib/python2.6/site-packages/ansible/plugins/action/normal.py", line 46, in run
result = merge_hash(result, self._execute_module(task_vars=task_vars, wrap_async=wrap_async))
File "/jenkins/test/ansible/lib/python2.6/site-packages/ansible/plugins/action/__init__.py", line 853, in _execute_module
res = self._low_level_execute_command(cmd, sudoable=sudoable, in_data=in_data)
File "/jenkins/test/ansible/lib/python2.6/site-packages/ansible/plugins/action/__init__.py", line 960, in _low_level_execute_command
rc, stdout, stderr = self._connection.exec_command(cmd, in_data=in_data, sudoable=sudoable)
File "/jenkins/test/ansible/lib/python2.6/site-packages/ansible/plugins/connection/ssh.py", line 1080, in exec_command
(returncode, stdout, stderr) = self._run(cmd, in_data, sudoable=sudoable)
File "/jenkins/test/ansible/lib/python2.6/site-packages/ansible/plugins/connection/ssh.py", line 354, in wrapped
_handle_error(remaining_retries, cmd[0], return_tuple, self._play_context.no_log, self.host)
File "/jenkins/test/ansible/lib/python2.6/site-packages/ansible/plugins/connection/ssh.py", line 307, in _handle_error
display.vvv(msg, host=host)
File "/jenkins/test/ansible/lib/python2.6/site-packages/ansible/utils/display.py", line 183, in vvv
return self.verbose(msg, host=host, caplevel=2)
File "/jenkins/test/ansible/lib/python2.6/site-packages/ansible/utils/display.py", line 206, in verbose
self.display("<%s> %s" % (host, msg), color=C.COLOR_VERBOSE, screen_only=True)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 63: ordinal not in range(128)

fatal: [server]: FAILED! => {
"msg": "Unexpected failure during module execution.",
"stdout": ""
}

# Fixed code
def _handle_error(
    remaining_retries, command, return_tuple, no_log, host, display=display
):
    # sshpass errors
    if command == b"sshpass":
        # Error 5 is invalid/incorrect password. Raise an exception to prevent retries from locking the account.
        if return_tuple[0] == 5:
            msg = "Invalid/incorrect username/password. Skipping remaining {0} retries to prevent account lockout:".format(
                remaining_retries
            )
            if remaining_retries <= 0:
                msg = "Invalid/incorrect password:"
            if no_log:
                msg = "{0} <error censored due to no log>".format(msg)
            else:
                msg = "{0} {1}".format(msg, to_native(return_tuple[2]).rstrip())
            raise AnsibleAuthenticationFailure(msg)

        # sshpass returns codes are 1-6. We handle 5 previously, so this catches other scenarios.
        # No exception is raised, so the connection is retried.
        elif return_tuple[0] in [1, 2, 3, 4, 6]:
            msg = "sshpass error:"
            if no_log:
                msg = "{0} <error censored due to no log>".format(msg)
            else:
                msg = "{0} {1}".format(msg, to_native(return_tuple[2]).rstrip())

    if return_tuple[0] == 255:
        SSH_ERROR = True
        for signature in b_NOT_SSH_ERRORS:
            if signature in return_tuple[1]:
                SSH_ERROR = False
                break

        if SSH_ERROR:
            msg = "Failed to connect to the host via ssh:"
            if no_log:
                msg = "{0} <error censored due to no log>".format(msg)
            else:
                msg = "{0} {1}".format(msg, to_native(return_tuple[2]).rstrip())
            raise AnsibleConnectionFailure(msg)

    # For other errors, no execption is raised so the connection is retried and we only log the messages
    if 1 <= return_tuple[0] <= 254:
        msg = "Failed to connect to the host via ssh:"
        if no_log:
            msg = "{0} <error censored due to no log>".format(msg)
        else:
            msg = "{0} {1}".format(msg, to_text(return_tuple[2]).rstrip())
        display.vvv(msg, host=host)