# Buggy code
def run(self, tmp=None, task_vars=None):
    """handler for file transfer operations"""
    if task_vars is None:
        task_vars = dict()

    result = super(ActionModule, self).run(tmp, task_vars)

    try:
        creates = self._task.args.get("creates")
        if creates:
            # do not run the command if the line contains creates=filename
            # and the filename already exists. This allows idempotence
            # of command executions.
            if self._remote_file_exists(creates):
                raise AnsibleActionSkip("%s exists, matching creates option" % creates)

        removes = self._task.args.get("removes")
        if removes:
            # do not run the command if the line contains removes=filename
            # and the filename does not exist. This allows idempotence
            # of command executions.
            if not self._remote_file_exists(removes):
                raise AnsibleActionSkip(
                    "%s does not exist, matching removes option" % removes
                )

        # The chdir must be absolute, because a relative path would rely on
        # remote node behaviour & user config.
        chdir = self._task.args.get("chdir")
        if chdir:
            # Powershell is the only Windows-path aware shell
            if (
                self._connection._shell.SHELL_FAMILY == "powershell"
                and not self.windows_absolute_path_detection.matches(chdir)
            ):
                raise AnsibleActionFail(
                    "chdir %s must be an absolute path for a Windows remote node"
                    % chdir
                )
            # Every other shell is unix-path-aware.
            if (
                self._connection._shell.SHELL_FAMILY != "powershell"
                and not chdir.startswith("/")
            ):
                raise AnsibleActionFail(
                    "chdir %s must be an absolute path for a Unix-aware remote node"
                    % chdir
                )

        # Split out the script as the first item in raw_params using
        # shlex.split() in order to support paths and files with spaces in the name.
        # Any arguments passed to the script will be added back later.
        raw_params = to_native(
            self._task.args.get("_raw_params", ""), errors="surrogate_or_strict"
        )
        parts = [
            to_text(s, errors="surrogate_or_strict")
            for s in shlex.split(raw_params.strip())
        ]
        source = parts[0]

        try:
            source = self._loader.get_real_file(
                self._find_needle("files", source),
                decrypt=self._task.args.get("decrypt", True),
            )
        except AnsibleError as e:
            raise AnsibleActionFail(to_native(e))

        # now we execute script, always assume changed.
        result["changed"] = True

        if not self._play_context.check_mode:
            # transfer the file to a remote tmp location
            tmp_src = self._connection._shell.join_path(
                self._connection._shell.tempdir, os.path.basename(source)
            )

            # Convert raw_params to text for the purpose of replacing the script since
            # parts and tmp_src are both unicode strings and raw_params will be different
            # depending on Python version.
            #
            # Once everything is encoded consistently, replace the script path on the remote
            # system with the remainder of the raw_params. This preserves quoting in parameters
            # that would have been removed by shlex.split().
            target_command = to_text(raw_params).strip().replace(parts[0], tmp_src)

            self._transfer_file(source, tmp_src)

            # set file permissions, more permissive when the copy is done as a different user
            self._fixup_perms2((tmp_src,), execute=True)

            # add preparation steps to one ssh roundtrip executing the script
            env_dict = dict()
            env_string = self._compute_environment_string(env_dict)
            script_cmd = " ".join([env_string, target_command])

        if self._play_context.check_mode:
            raise AnsibleActionDone()

        script_cmd = self._connection._shell.wrap_for_exec(script_cmd)

        exec_data = None
        # HACK: come up with a sane way to pass around env outside the command
        if self._connection.transport == "winrm":
            exec_data = self._connection._create_raw_wrapper_payload(
                script_cmd, env_dict
            )

        result.update(
            self._low_level_execute_command(
                cmd=script_cmd, in_data=exec_data, sudoable=True, chdir=chdir
            )
        )

        if "rc" in result and result["rc"] != 0:
            raise AnsibleActionFail("non-zero return code")

    except AnsibleAction as e:
        result.update(e.result)
    finally:
        self._remove_tmp_path(self._connection._shell.tempdir)

    return result


# Traceback (WinRMTransportError)
ASK [replace_credentials : replace special strings with their corresponding credentials] ****************************************************************************************************
task path: /tmp/deployment/roles/replace_credentials/tasks/main.yml:49
<i89666.sbb.ch> ESTABLISH WINRM CONNECTION FOR USER: fs45087@SBB.CH on PORT 5986 TO i89666.sbb.ch
<i89666.sbb.ch> WINRM CONNECT: transport=credssp endpoint=https://i89666.sbb.ch:5986/wsman
<i89666.sbb.ch> WINRM OPEN SHELL: 0F4A65B5-2D6A-454A-BD7F-289C0F330046
EXEC (via pipeline wrapper)
<i89666.sbb.ch> WINRM EXEC 'PowerShell' ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Unrestricted', '-EncodedCommand', 'UABvAHcAZQByAFMAaABlAGwAbAAgAC0ATgBvAFAAcgBvAGYAaQBsAGUAIAAtAE4AbwBuAEkAbgB0AGUAcgBhAGMAdABpAHYAZQAgAC0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gB1AEEASABVAEEAWgBRAEEAcABBAEMAQQBBAGUAdwBBAGcAQQBHAFUAQQBlAEEAQgBwAEEASABRAEEASQBBAEEAawBBAEUAdwBBAFEAUQBCAFQAQQBGAFEAQQBSAFEAQgBZAEEARQBrAEEAVgBBAEIARABBAEUAOABBAFIAQQBCAEYAQQBDAEEAQQBmAFEAQQBnAEEARQBVAEEAYgBBAEIAegBBAEcAVQBBAEkAQQBCADcAQQBDAEEAQQBaAFEAQgA0AEEARwBrAEEAZABBAEEAZwBBAEQARQBBAEkAQQBCADkAQQBDAEEAQQBmAFEAQQA9AA==']
<i89666.sbb.ch> WINRM RESULT u'<Response code 0, out "C:\\Users\\fs45087\n", err "">'
EXEC (via pipeline wrapper)
<i89666.sbb.ch> WINRM EXEC 'PowerShell' ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Unrestricted', '-EncodedCommand', 'UABvAHcAZQByAFMAaABlAGwAbAAgAC0ATgBvAFAAcgBvAGYAaQBsAGUAIAAtAE4AbwBuAEkAbgB0AGUAcgBhAGMAdABpAHYAZQAgAC0ARQB4AGUAYwB1AHQAaQBvAG4AUABvAGwAaQBjAHkAIABVAG4AcgBlAHMAdAByAGkAYwB0AGUAZAAgAC0ARQBuAGMAbwBkAGUAZABDAG8AbQBtAGEAbgBkACAAVQB3AEIAbABBAEgAUQBBAEwAUQBCAFQAQQBIAFEAQQBjAGcAQgBwAEEARwBNAEEAZABBAEIATgBBAEcAOABBAFoAQQBCAGwAQQBDAEEAQQBMAFEAQgBXAEEARwBVAEEAYwBnAEIAegBBAEcAawBBAGIAdwBCAHUAQQBDAEEAQQBUAEEAQgBoAEEASABRAEEAWgBRAEIAegBBAEgAUQBBAEMAZwBBAG8AQQBFADQAQQBaAFEAQgAzAEEAQwAwAEEAUwBRAEIAMABBAEcAVQBBAGIAUQBBAGcAQQBDADAAQQBWAEEAQgA1AEEASABBAEEAWgBRAEEAZwBBAEUAUQBBAGEAUQBCAHkAQQBHAFUAQQBZAHcAQ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EAQgBGAEEASABJAEEAYwBnAEIAdgBBAEgASQBBAFEAUQBCAGoAQQBIAFEAQQBhAFEAQgB2AEEARwA0AEEASQBBAEIAVABBAEcAawBBAGIAQQBCAGwAQQBHADQAQQBkAEEAQgBzAEEASABrAEEAUQB3AEIAdgBBAEcANABBAGQAQQBCAHAAQQBHADQAQQBkAFEAQgBsAEEAQwBrAEEASQBBAEIANwBBAEMAQQBBAFoAUQBCADQAQQBHAGsAQQBkAEEAQQBnAEEAQwBRAEEAVABBAEIAQgBBAEYATQBBAFYAQQBCAEYAQQBGAGcAQQBTAFEAQgBVAEEARQBNAEEAVAB3AEIARQBBAEUAVQBBAEkAQQBCADkAQQBDAEEAQQBSAFEAQgBzAEEASABNAEEAWgBRAEEAZwBBAEgAcwBBAEkAQQBCAGwAQQBIAGcAQQBhAFEAQgAwAEEAQwBBAEEATQBRAEEAZwBBAEgAMABBAEkAQQBCADkAQQBBAD0APQA=']
<i89666.sbb.ch> WINRM RESULT u'<Response code 0, out "C:\\Users\\fs45087\\App", err "">'
looking for "files/Test.ps1" at "/tmp/deployment/roles/replace_credentials/files/Test.ps1"
<i89666.sbb.ch> PUT "/tmp/deployment/roles/replace_credentials/files/Test.ps1" TO "C:\Users\fs45087\AppData\Local\Temp\ansible-tmp-1510323347.24-3741944900007\Test.ps1"
<i89666.sbb.ch> WINRM PUT "/tmp/deployment/roles/replace_credentials/files/Test.ps1" to "C:\Users\fs45087\AppData\Local\Temp\ansible-tmp-1510323347.24-3741944900007\Test.ps1" (offset=2337 size=2337)
EXEC (via pipeline wrapper)
<i89666.sbb.ch> WINRM EXEC 'PowerShell' ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Unrestricted', '-EncodedCommand', 'JgAgACAAJwBDADoAXABVAHMAZQByAHMAXABmAHMANAA1ADAAOAA3AFwAQQBwAHAARABhAHQAYQBcAEwAbwBjAGEAbABcAFQAZQBtAHAAXABhAG4AcwBpAGIAbABlAC0AdABtAHAALQAxADUAMQAwADMA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AiAH0AfQB9ACcA']
[WARNING]: FATAL ERROR DURING FILE TRANSFER: Traceback (most recent call last):   File "/var/lib/awx/venv/ansible/local/lib/python2.7/site-packages/ansible/plugins/connection/winrm.py",
line 267, in _winrm_exec     self._winrm_send_input(self.protocol, self.shell_id, command_id, data, eof=is_last)   File "/var/lib/awx/venv/ansible/local/lib/python2.7/site-
packages/ansible/plugins/connection/winrm.py", line 248, in _winrm_send_input     protocol.send_message(xmltodict.unparse(rq))   File "/var/lib/awx/venv/ansible/local/lib/python2.7/site-
packages/winrm/protocol.py", line 207, in send_message     return self.transport.send_message(message)   File "/var/lib/awx/venv/ansible/local/lib/python2.7/site-
packages/winrm/transport.py", line 202, in send_message     raise WinRMTransportError('http', error_message) WinRMTransportError: (u'http', u'Bad HTTP response returned from server. Code
500')

<i89666.sbb.ch> WINRM CLOSE SHELL: 0F4A65B5-2D6A-454A-BD7F-289C0F330046
fatal: [i89666.sbb.ch]: FAILED! => {
"failed": true,
"msg": "winrm send_input failed"
}

# Fixed code
def run(self, tmp=None, task_vars=None):
    """handler for file transfer operations"""
    if task_vars is None:
        task_vars = dict()

    result = super(ActionModule, self).run(tmp, task_vars)

    try:
        creates = self._task.args.get("creates")
        if creates:
            # do not run the command if the line contains creates=filename
            # and the filename already exists. This allows idempotence
            # of command executions.
            if self._remote_file_exists(creates):
                raise AnsibleActionSkip("%s exists, matching creates option" % creates)

        removes = self._task.args.get("removes")
        if removes:
            # do not run the command if the line contains removes=filename
            # and the filename does not exist. This allows idempotence
            # of command executions.
            if not self._remote_file_exists(removes):
                raise AnsibleActionSkip(
                    "%s does not exist, matching removes option" % removes
                )

        # The chdir must be absolute, because a relative path would rely on
        # remote node behaviour & user config.
        chdir = self._task.args.get("chdir")
        if chdir:
            # Powershell is the only Windows-path aware shell
            if (
                self._connection._shell.SHELL_FAMILY == "powershell"
                and not self.windows_absolute_path_detection.matches(chdir)
            ):
                raise AnsibleActionFail(
                    "chdir %s must be an absolute path for a Windows remote node"
                    % chdir
                )
            # Every other shell is unix-path-aware.
            if (
                self._connection._shell.SHELL_FAMILY != "powershell"
                and not chdir.startswith("/")
            ):
                raise AnsibleActionFail(
                    "chdir %s must be an absolute path for a Unix-aware remote node"
                    % chdir
                )

        # Split out the script as the first item in raw_params using
        # shlex.split() in order to support paths and files with spaces in the name.
        # Any arguments passed to the script will be added back later.
        raw_params = to_native(
            self._task.args.get("_raw_params", ""), errors="surrogate_or_strict"
        )
        parts = [
            to_text(s, errors="surrogate_or_strict")
            for s in shlex.split(raw_params.strip())
        ]
        source = parts[0]

        try:
            source = self._loader.get_real_file(
                self._find_needle("files", source),
                decrypt=self._task.args.get("decrypt", True),
            )
        except AnsibleError as e:
            raise AnsibleActionFail(to_native(e))

        # now we execute script, always assume changed.
        result["changed"] = True

        if not self._play_context.check_mode:
            # transfer the file to a remote tmp location
            tmp_src = self._connection._shell.join_path(
                self._connection._shell.tempdir, os.path.basename(source)
            )

            # Convert raw_params to text for the purpose of replacing the script since
            # parts and tmp_src are both unicode strings and raw_params will be different
            # depending on Python version.
            #
            # Once everything is encoded consistently, replace the script path on the remote
            # system with the remainder of the raw_params. This preserves quoting in parameters
            # that would have been removed by shlex.split().
            target_command = to_text(raw_params).strip().replace(parts[0], tmp_src)

            self._transfer_file(source, tmp_src)

            # set file permissions, more permissive when the copy is done as a different user
            self._fixup_perms2((tmp_src,), execute=True)

            # add preparation steps to one ssh roundtrip executing the script
            env_dict = dict()
            env_string = self._compute_environment_string(env_dict)
            script_cmd = " ".join([env_string, target_command])

        if self._play_context.check_mode:
            raise AnsibleActionDone()

        script_cmd = self._connection._shell.wrap_for_exec(script_cmd)

        exec_data = None
        # WinRM requires a special wrapper to work with environment variables
        if self._connection.transport == "winrm":
            pay = self._connection._create_raw_wrapper_payload(script_cmd, env_dict)
            exec_data = exec_wrapper.replace(
                b"$json_raw = ''", b"$json_raw = @'\r\n%s\r\n'@" % to_bytes(pay)
            )
            script_cmd = "-"

        result.update(
            self._low_level_execute_command(
                cmd=script_cmd, in_data=exec_data, sudoable=True, chdir=chdir
            )
        )

        if "rc" in result and result["rc"] != 0:
            raise AnsibleActionFail("non-zero return code")

    except AnsibleAction as e:
        result.update(e.result)
    finally:
        self._remove_tmp_path(self._connection._shell.tempdir)

    return result