# Buggy code
def main():
    module = AnsibleModule(
        argument_spec=dict(
            command=dict(required=True),
            chdir=dict(),
            creates=dict(),
            removes=dict(),
            responses=dict(type="dict", required=True),
            timeout=dict(type="int", default=30),
            echo=dict(type="bool", default=False),
        )
    )

    if not HAS_PEXPECT:
        module.fail_json(msg="The pexpect python module is required")

    chdir = module.params["chdir"]
    args = module.params["command"]
    creates = module.params["creates"]
    removes = module.params["removes"]
    responses = module.params["responses"]
    timeout = module.params["timeout"]
    echo = module.params["echo"]

    events = dict()
    for key, value in responses.items():
        if isinstance(value, list):
            response = response_closure(module, key, value)
        else:
            response = "%s\n" % value.rstrip("\n").decode()

        events[key.decode()] = response

    if args.strip() == "":
        module.fail_json(rc=256, msg="no command given")

    if chdir:
        chdir = os.path.abspath(os.path.expanduser(chdir))
        os.chdir(chdir)

    if creates:
        # do not run the command if the line contains creates=filename
        # and the filename already exists.  This allows idempotence
        # of command executions.
        v = os.path.expanduser(creates)
        if os.path.exists(v):
            module.exit_json(
                cmd=args, stdout="skipped, since %s exists" % v, changed=False, rc=0
            )

    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.
        v = os.path.expanduser(removes)
        if not os.path.exists(v):
            module.exit_json(
                cmd=args,
                stdout="skipped, since %s does not exist" % v,
                changed=False,
                rc=0,
            )

    startd = datetime.datetime.now()

    try:
        try:
            # Prefer pexpect.run from pexpect>=4
            out, rc = pexpect.run(
                args,
                timeout=timeout,
                withexitstatus=True,
                events=events,
                cwd=chdir,
                echo=echo,
                encoding="utf-8",
            )
        except TypeError:
            # Use pexpect.runu in pexpect>=3.3,<4
            out, rc = pexpect.runu(
                args,
                timeout=timeout,
                withexitstatus=True,
                events=events,
                cwd=chdir,
                echo=echo,
            )
    except (TypeError, AttributeError):
        e = get_exception()
        # This should catch all insufficient versions of pexpect
        # We deem them insufficient for their lack of ability to specify
        # to not echo responses via the run/runu functions, which would
        # potentially leak sensentive information
        module.fail_json(
            msg="Insufficient version of pexpect installed "
            "(%s), this module requires pexpect>=3.3. "
            "Error was %s" % (pexpect.__version__, e)
        )
    except pexpect.ExceptionPexpect:
        e = get_exception()
        module.fail_json(msg="%s" % e)

    endd = datetime.datetime.now()
    delta = endd - startd

    if out is None:
        out = ""

    ret = dict(
        cmd=args,
        stdout=out.rstrip("\r\n"),
        rc=rc,
        start=str(startd),
        end=str(endd),
        delta=str(delta),
        changed=True,
    )

    if rc is not None:
        module.exit_json(**ret)
    else:
        ret["msg"] = "command exceeded timeout"
        module.fail_json(**ret)


# Traceback (nAttributeError)
TASK [goldengate-monitor : Finalize configuration of GoldenGate Monitor Server]
task path: /home/*****/git/ami-provisioning/roles/goldengate-monitor/tasks/main.yml:259
Using module file /usr/lib/python2.7/dist-packages/ansible/modules/extras/commands/expect.py
<X.X.X.X> ESTABLISH SSH CONNECTION FOR USER: ec2-user
<X.X.X.X> SSH: EXEC ssh -o ControlMaster=auto -o ControlPersist=150s -o 'IdentityFile=~/.ssh/key.pem' -o StrictHostKeyChecking=no -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=ec2-user -o ConnectTimeout=10 -o ControlPath=/home/******/.ansible/cp/ansible-ssh-%h-%p-%r X.X.X.X '/bin/sh -c '"'"'( umask 77 &amp;&amp; mkdir -p "` echo /tmp/ansible-tmp-1485359246.77-165679692062492 `" &amp;&amp; echo ansible-tmp-1485359246.77-165679692062492="` echo /tmp/ansible-tmp-1485359246.77-165679692062492 `" ) &amp;&amp; sleep 0'"'"''
<X.X.X.X> PUT /tmp/tmp8WnA3S TO /tmp/ansible-tmp-1485359246.77-165679692062492/expect.py
<X.X.X.X> SSH: EXEC sftp -b - -o ControlMaster=auto -o ControlPersist=150s -o 'IdentityFile=~/.ssh/key.pem' -o StrictHostKeyChecking=no -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=ec2-user -o ConnectTimeout=10 -o ControlPath=/home/*******/.ansible/cp/ansible-ssh-%h-%p-%r '[X.X.X.X]'
<X.X.X.X> ESTABLISH SSH CONNECTION FOR USER: ec2-user
<X.X.X.X> SSH: EXEC ssh -o ControlMaster=auto -o ControlPersist=150s -o 'IdentityFile=~/.ssh/key.pem' -o StrictHostKeyChecking=no -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=ec2-user -o ConnectTimeout=10 -o ControlPath=/home/********/.ansible/cp/ansible-ssh-%h-%p-%r X.X.X.X '/bin/sh -c '"'"'setfacl -m u:oracle:rx /tmp/ansible-tmp-1485359246.77-165679692062492/ /tmp/ansible-tmp-1485359246.77-165679692062492/expect.py &amp;&amp; sleep 0'"'"''
<X.X.X.X> ESTABLISH SSH CONNECTION FOR USER: ec2-user
<X.X.X.X> SSH: EXEC ssh -o ControlMaster=auto -o ControlPersist=150s -o 'IdentityFile=~/.ssh/key.pem' -o StrictHostKeyChecking=no -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=ec2-user -o ConnectTimeout=10 -o ControlPath=/home/*********/.ansible/cp/ansible-ssh-%h-%p-%r -tt X.X.X.X '/bin/sh -c '"'"'sudo -H -S -n -u oracle /bin/sh -c '"'"'"'"'"'"'"'"'echo BECOME-SUCCESS-cnroohudwdkqeukfzcxchpyrqnkqquzd; /usr/bin/python /tmp/ansible-tmp-1485359246.77-165679692062492/expect.py'"'"'"'"'"'"'"'"' &amp;&amp; sleep 0'"'"''
<X.X.X.X> ESTABLISH SSH CONNECTION FOR USER: ec2-user
<X.X.X.X> SSH: EXEC ssh -o ControlMaster=auto -o ControlPersist=150s -o 'IdentityFile=~/.ssh/key.pem' -o StrictHostKeyChecking=no -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o User=ec2-user -o ConnectTimeout=10 -o ControlPath=/home/*******/.ansible/cp/ansible-ssh-%h-%p-%r X.X.X.X '/bin/sh -c '"'"'rm -f -r /tmp/ansible-tmp-1485359246.77-165679692062492/ > /dev/null 2>&amp;1 &amp;&amp; sleep 0'"'"''
fatal: [X.X.X.X]: FAILED! => {
"changed": false,
"failed": true,
"invocation": {
"module_name": "expect"
},
"module_stderr": "Shared connection to X.X.X.X closed.\r\n",
"module_stdout": "Traceback (most recent call last):\r\n  File \"/tmp/ansible_vOOWV3/ansible_module_expect.py\", line 237, in <module>\r\n    main()\r\n  File \"/tmp/ansible_vOOWV3/ansible_module_expect.py\", line 149, in main\r\n    response = u'%s\\n' % value.rstrip('\\n').decode()\r\nAttributeError: 'int' object has no attribute 'rstrip'\r\n",
"msg": "MODULE FAILURE"
}

# Fixed code
def main():
    module = AnsibleModule(
        argument_spec=dict(
            command=dict(required=True),
            chdir=dict(),
            creates=dict(),
            removes=dict(),
            responses=dict(type="dict", required=True),
            timeout=dict(type="int", default=30),
            echo=dict(type="bool", default=False),
        )
    )

    if not HAS_PEXPECT:
        module.fail_json(msg="The pexpect python module is required")

    chdir = module.params["chdir"]
    args = module.params["command"]
    creates = module.params["creates"]
    removes = module.params["removes"]
    responses = module.params["responses"]
    timeout = module.params["timeout"]
    echo = module.params["echo"]

    events = dict()
    for key, value in responses.items():
        if isinstance(value, list):
            response = response_closure(module, key, value)
        else:
            response = "%s\n" % str(value).rstrip("\n").decode()

        events[key.decode()] = response

    if args.strip() == "":
        module.fail_json(rc=256, msg="no command given")

    if chdir:
        chdir = os.path.abspath(os.path.expanduser(chdir))
        os.chdir(chdir)

    if creates:
        # do not run the command if the line contains creates=filename
        # and the filename already exists.  This allows idempotence
        # of command executions.
        v = os.path.expanduser(creates)
        if os.path.exists(v):
            module.exit_json(
                cmd=args, stdout="skipped, since %s exists" % v, changed=False, rc=0
            )

    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.
        v = os.path.expanduser(removes)
        if not os.path.exists(v):
            module.exit_json(
                cmd=args,
                stdout="skipped, since %s does not exist" % v,
                changed=False,
                rc=0,
            )

    startd = datetime.datetime.now()

    try:
        try:
            # Prefer pexpect.run from pexpect>=4
            out, rc = pexpect.run(
                args,
                timeout=timeout,
                withexitstatus=True,
                events=events,
                cwd=chdir,
                echo=echo,
                encoding="utf-8",
            )
        except TypeError:
            # Use pexpect.runu in pexpect>=3.3,<4
            out, rc = pexpect.runu(
                args,
                timeout=timeout,
                withexitstatus=True,
                events=events,
                cwd=chdir,
                echo=echo,
            )
    except (TypeError, AttributeError):
        e = get_exception()
        # This should catch all insufficient versions of pexpect
        # We deem them insufficient for their lack of ability to specify
        # to not echo responses via the run/runu functions, which would
        # potentially leak sensentive information
        module.fail_json(
            msg="Insufficient version of pexpect installed "
            "(%s), this module requires pexpect>=3.3. "
            "Error was %s" % (pexpect.__version__, e)
        )
    except pexpect.ExceptionPexpect:
        e = get_exception()
        module.fail_json(msg="%s" % e)

    endd = datetime.datetime.now()
    delta = endd - startd

    if out is None:
        out = ""

    ret = dict(
        cmd=args,
        stdout=out.rstrip("\r\n"),
        rc=rc,
        start=str(startd),
        end=str(endd),
        delta=str(delta),
        changed=True,
    )

    if rc is not None:
        module.exit_json(**ret)
    else:
        ret["msg"] = "command exceeded timeout"
        module.fail_json(**ret)