# Buggy code
def _make_tmp_path(self, remote_user=None):
    """
    Create and return a temporary path on a remote box.
    """

    if remote_user is None:
        remote_user = self._play_context.remote_user

    try:
        admin_users = self._connection._shell.get_option("admin_users") + [remote_user]
    except AnsibleError:
        admin_users = ["root", remote_user]  # plugin does not support admin_users
    try:
        remote_tmp = self._connection._shell.get_option("remote_tmp")
    except AnsibleError:
        remote_tmp = "~/.ansible/tmp"

    # deal with tmpdir creation
    basefile = "ansible-tmp-%s-%s" % (time.time(), random.randint(0, 2**48))
    use_system_tmp = bool(
        self._play_context.become and self._play_context.become_user not in admin_users
    )
    # Network connection plugins (network_cli, netconf, etc.) execute on the controller, rather than the remote host.
    # As such, we want to avoid using remote_user for paths  as remote_user may not line up with the local user
    # This is a hack and should be solved by more intelligent handling of remote_tmp in 2.7
    if getattr(self._connection, "_remote_is_local", False):
        tmpdir = C.DEFAULT_LOCAL_TMP
    else:
        tmpdir = self._remote_expand_user(remote_tmp, sudoable=False)
    cmd = self._connection._shell.mkdtemp(
        basefile=basefile, system=use_system_tmp, tmpdir=tmpdir
    )
    result = self._low_level_execute_command(cmd, sudoable=False)

    # error handling on this seems a little aggressive?
    if result["rc"] != 0:
        if result["rc"] == 5:
            output = "Authentication failure."
        elif result["rc"] == 255 and self._connection.transport in ("ssh",):
            if self._play_context.verbosity > 3:
                output = "SSH encountered an unknown error. The output was:\n%s%s" % (
                    result["stdout"],
                    result["stderr"],
                )
            else:
                output = (
                    "SSH encountered an unknown error during the connection. "
                    "We recommend you re-run the command using -vvvv, which will enable SSH debugging output to help diagnose the issue"
                )

        elif "No space left on device" in result["stderr"]:
            output = result["stderr"]
        else:
            output = (
                "Authentication or permission failure. "
                "In some cases, you may have been able to authenticate and did not have permissions on the target directory. "
                'Consider changing the remote tmp path in ansible.cfg to a path rooted in "/tmp". '
                "Failed command was: %s, exited with result %d" % (cmd, result["rc"])
            )
        if "stdout" in result and result["stdout"] != "":
            output = output + ", stdout output: %s" % result["stdout"]
        if (
            self._play_context.verbosity > 3
            and "stderr" in result
            and result["stderr"] != ""
        ):
            output += ", stderr output: %s" % result["stderr"]
        raise AnsibleConnectionFailure(output)
    else:
        self._cleanup_remote_tmp = True

    try:
        stdout_parts = result["stdout"].strip().split("%s=" % basefile, 1)
        rc = self._connection._shell.join_path(stdout_parts[-1], "").splitlines()[-1]
    except IndexError:
        # stdout was empty or just space, set to / to trigger error in next if
        rc = "/"

    # Catch failure conditions, files should never be
    # written to locations in /.
    if rc == "/":
        raise AnsibleError(
            "failed to resolve remote temporary directory from %s: `%s` returned empty string"
            % (basefile, cmd)
        )

    self._connection._shell.tmpdir = rc

    if not use_system_tmp:
        self._connection._shell.env.update(
            {"ANSIBLE_REMOTE_TMP": self._connection._shell.tmpdir}
        )
    return rc


# Traceback (OSError)
ansible-playbook 2.6.0rc1
config file = None
configured module search path = [u'/home/centos/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible-playbook
python version = 2.7.5 (default, Apr 11 2018, 07:36:10) [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)]
No config file found; using defaults
Parsed /home/centos/inventory.ini inventory source with ini plugin

PLAYBOOK: playbook.yml *************************************************************************************************************************************
1 plays in playbook.yml

PLAY [all] *************************************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************************************
task path: /home/centos/playbook.yml:2
<target> ESTABLISH LOCAL CONNECTION FOR USER: centos
<target> EXEC /bin/sh -c 'echo ~centos &amp;&amp; sleep 0'
<target> EXEC /bin/sh -c '( umask 77 &amp;&amp; mkdir -p "` echo /home/centos/.ansible/tmp/ansible-tmp-1528489241.67-154074287834207 `" &amp;&amp; echo ansible-tmp-1528489241.67-154074287834207="` echo /home/centos/.ansible/tmp/ansible-tmp-1528489241.67-154074287834207 `" ) &amp;&amp; sleep 0'
Using module file /usr/lib/python2.7/site-packages/ansible/modules/system/setup.py
<target> PUT /home/centos/.ansible/tmp/ansible-local-26937OUx1qh/tmpsaSW45 TO /home/centos/.ansible/tmp/ansible-tmp-1528489241.67-154074287834207/setup.py
<target> EXEC /bin/sh -c 'chmod u+x /home/centos/.ansible/tmp/ansible-tmp-1528489241.67-154074287834207/ /home/centos/.ansible/tmp/ansible-tmp-1528489241.67-154074287834207/setup.py &amp;&amp; sleep 0'
<target> EXEC /bin/sh -c '/usr/bin/python /home/centos/.ansible/tmp/ansible-tmp-1528489241.67-154074287834207/setup.py &amp;&amp; sleep 0'
<target> EXEC /bin/sh -c 'rm -f -r /home/centos/.ansible/tmp/ansible-tmp-1528489241.67-154074287834207/ > /dev/null 2>&amp;1 &amp;&amp; sleep 0'
ok: [target]
META: ran handlers

TASK [blockinfile] *****************************************************************************************************************************************
task path: /home/centos/playbook.yml:4
<target> ESTABLISH LOCAL CONNECTION FOR USER: centos
<target> EXEC /bin/sh -c 'echo ~centos &amp;&amp; sleep 0'
<target> EXEC /bin/sh -c '( umask 77 &amp;&amp; mkdir -p "` echo /var/tmp/ansible-tmp-1528489242.66-190869334332659 `" &amp;&amp; echo ansible-tmp-1528489242.66-190869334332659="` echo /var/tmp/ansible-tmp-1528489242.66-190869334332659 `" ) &amp;&amp; sleep 0'
Using module file /usr/lib/python2.7/site-packages/ansible/modules/files/blockinfile.py
<target> PUT /home/centos/.ansible/tmp/ansible-local-26937OUx1qh/tmp4y0GYj TO /var/tmp/ansible-tmp-1528489242.66-190869334332659/blockinfile.py
<target> EXEC /bin/sh -c 'setfacl -m u:testuser:r-x /var/tmp/ansible-tmp-1528489242.66-190869334332659/ /var/tmp/ansible-tmp-1528489242.66-190869334332659/blockinfile.py &amp;&amp; sleep 0'
<target> EXEC /bin/sh -c 'sudo -H -S -n -u testuser /bin/sh -c '"'"'echo BECOME-SUCCESS-dkqkzvhlmkxabaonclqypkdsoabveqpw; /usr/bin/python /var/tmp/ansible-tmp-1528489242.66-190869334332659/blockinfile.py'"'"' &amp;&amp; sleep 0'
<target> EXEC /bin/sh -c 'rm -f -r /var/tmp/ansible-tmp-1528489242.66-190869334332659/ > /dev/null 2>&amp;1 &amp;&amp; sleep 0'
The full traceback is:
Traceback (most recent call last):
File "/tmp/ansible_c67IEZ/ansible_module_blockinfile.py", line 351, in <module>
main()
File "/tmp/ansible_c67IEZ/ansible_module_blockinfile.py", line 335, in main
write_changes(module, result, real_path)
File "/tmp/ansible_c67IEZ/ansible_module_blockinfile.py", line 163, in write_changes
tmpfd, tmpfile = tempfile.mkstemp(dir=getattr(module, 'tmpdir', None))
File "/usr/lib64/python2.7/tempfile.py", line 304, in mkstemp
return _mkstemp_inner(dir, prefix, suffix, flags)
File "/usr/lib64/python2.7/tempfile.py", line 239, in _mkstemp_inner
fd = _os.open(file, flags, 0600)
OSError: [Errno 13] Permission denied: '/var/tmp/ansible-tmp-1528489242.66-190869334332659/tmpXemXXr'

fatal: [target]: FAILED! => {
"changed": false,
"module_stderr": "Traceback (most recent call last):\n  File \"/tmp/ansible_c67IEZ/ansible_module_blockinfile.py\", line 351, in <module>\n    main()\n  File \"/tmp/ansible_c67IEZ/ansible_module_blockinfile.py\", line 335, in main\n    write_changes(module, result, real_path)\n  File \"/tmp/ansible_c67IEZ/ansible_module_blockinfile.py\", line 163, in write_changes\n    tmpfd, tmpfile = tempfile.mkstemp(dir=getattr(module, 'tmpdir', None))\n  File \"/usr/lib64/python2.7/tempfile.py\", line 304, in mkstemp\n    return _mkstemp_inner(dir, prefix, suffix, flags)\n  File \"/usr/lib64/python2.7/tempfile.py\", line 239, in _mkstemp_inner\n    fd = _os.open(file, flags, 0600)\nOSError: [Errno 13] Permission denied: '/var/tmp/ansible-tmp-1528489242.66-190869334332659/tmpXemXXr'\n",
"module_stdout": "",
"msg": "MODULE FAILURE",
"rc": 1
}
to retry, use: --limit @/home/centos/playbook.retry

PLAY RECAP *************************************************************************************************************************************************
target                     : ok=1    changed=0    unreachable=0    failed=1

# Fixed code
def _make_tmp_path(self, remote_user=None):
    """
    Create and return a temporary path on a remote box.
    """

    become_unprivileged = self._is_become_unprivileged()
    try:
        remote_tmp = self._connection._shell.get_option("remote_tmp")
    except AnsibleError:
        remote_tmp = "~/.ansible/tmp"

    # deal with tmpdir creation
    basefile = "ansible-tmp-%s-%s" % (time.time(), random.randint(0, 2**48))
    # Network connection plugins (network_cli, netconf, etc.) execute on the controller, rather than the remote host.
    # As such, we want to avoid using remote_user for paths  as remote_user may not line up with the local user
    # This is a hack and should be solved by more intelligent handling of remote_tmp in 2.7
    if getattr(self._connection, "_remote_is_local", False):
        tmpdir = C.DEFAULT_LOCAL_TMP
    else:
        tmpdir = self._remote_expand_user(remote_tmp, sudoable=False)
    cmd = self._connection._shell.mkdtemp(
        basefile=basefile, system=become_unprivileged, tmpdir=tmpdir
    )
    result = self._low_level_execute_command(cmd, sudoable=False)

    # error handling on this seems a little aggressive?
    if result["rc"] != 0:
        if result["rc"] == 5:
            output = "Authentication failure."
        elif result["rc"] == 255 and self._connection.transport in ("ssh",):
            if self._play_context.verbosity > 3:
                output = "SSH encountered an unknown error. The output was:\n%s%s" % (
                    result["stdout"],
                    result["stderr"],
                )
            else:
                output = (
                    "SSH encountered an unknown error during the connection. "
                    "We recommend you re-run the command using -vvvv, which will enable SSH debugging output to help diagnose the issue"
                )

        elif "No space left on device" in result["stderr"]:
            output = result["stderr"]
        else:
            output = (
                "Authentication or permission failure. "
                "In some cases, you may have been able to authenticate and did not have permissions on the target directory. "
                'Consider changing the remote tmp path in ansible.cfg to a path rooted in "/tmp". '
                "Failed command was: %s, exited with result %d" % (cmd, result["rc"])
            )
        if "stdout" in result and result["stdout"] != "":
            output = output + ", stdout output: %s" % result["stdout"]
        if (
            self._play_context.verbosity > 3
            and "stderr" in result
            and result["stderr"] != ""
        ):
            output += ", stderr output: %s" % result["stderr"]
        raise AnsibleConnectionFailure(output)
    else:
        self._cleanup_remote_tmp = True

    try:
        stdout_parts = result["stdout"].strip().split("%s=" % basefile, 1)
        rc = self._connection._shell.join_path(stdout_parts[-1], "").splitlines()[-1]
    except IndexError:
        # stdout was empty or just space, set to / to trigger error in next if
        rc = "/"

    # Catch failure conditions, files should never be
    # written to locations in /.
    if rc == "/":
        raise AnsibleError(
            "failed to resolve remote temporary directory from %s: `%s` returned empty string"
            % (basefile, cmd)
        )

    self._connection._shell.tmpdir = rc

    if not become_unprivileged:
        self._connection._shell.env.update(
            {"ANSIBLE_REMOTE_TMP": self._connection._shell.tmpdir}
        )
    return rc