# Buggy code
def main():
    module = AnsibleModule(
        # not checking because of daisy chain to file module
        argument_spec=dict(
            src=dict(required=True, type="path"),
            delimiter=dict(required=False),
            dest=dict(required=True, type="path"),
            backup=dict(default=False, type="bool"),
            remote_src=dict(default=False, type="bool"),
            regexp=dict(required=False),
            ignore_hidden=dict(default=False, type="bool"),
            validate=dict(required=False, type="str"),
        ),
        add_file_common_args=True,
    )

    changed = False
    path_hash = None
    dest_hash = None
    src = module.params["src"]
    dest = module.params["dest"]
    backup = module.params["backup"]
    delimiter = module.params["delimiter"]
    regexp = module.params["regexp"]
    compiled_regexp = None
    ignore_hidden = module.params["ignore_hidden"]
    validate = module.params.get("validate", None)

    result = dict(src=src, dest=dest)
    if not os.path.exists(src):
        module.fail_json(msg="Source (%s) does not exist" % src)

    if not os.path.isdir(src):
        module.fail_json(msg="Source (%s) is not a directory" % src)

    if regexp is not None:
        try:
            compiled_regexp = re.compile(regexp)
        except re.error as e:
            module.fail_json(msg='Invalid Regexp (%s) in "%s"' % (to_native(e), regexp))

    if validate and "%s" not in validate:
        module.fail_json(msg="validate must contain %%s: %s" % validate)

    path = assemble_from_fragments(src, delimiter, compiled_regexp, ignore_hidden)
    path_hash = module.sha1(path)
    result["checksum"] = path_hash

    # Backwards compat.  This won't return data if FIPS mode is active
    try:
        pathmd5 = module.md5(path)
    except ValueError:
        pathmd5 = None
    result["md5sum"] = pathmd5

    if os.path.exists(dest):
        dest_hash = module.sha1(dest)

    if path_hash != dest_hash:
        if validate:
            (rc, out, err) = module.run_command(validate % path)
            result["validation"] = dict(rc=rc, stdout=out, stderr=err)
            if rc != 0:
                cleanup(path)
                module.fail_json(msg="failed to validate: rc:%s error:%s" % (rc, err))
        if backup and dest_hash is not None:
            result["backup_file"] = module.backup_local(dest)

        module.atomic_move(path, dest, unsafe_writes=module.params["unsafe_writes"])
        changed = True

    cleanup(path, result)

    # handle file permissions
    file_args = module.load_file_common_arguments(module.params)
    result["changed"] = module.set_fs_attributes_if_different(file_args, changed)

    # Mission complete
    result["msg"] = "OK"
    module.exit_json(**result)


# 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 main():
    module = AnsibleModule(
        # not checking because of daisy chain to file module
        argument_spec=dict(
            src=dict(required=True, type="path"),
            delimiter=dict(required=False),
            dest=dict(required=True, type="path"),
            backup=dict(default=False, type="bool"),
            remote_src=dict(default=False, type="bool"),
            regexp=dict(required=False),
            ignore_hidden=dict(default=False, type="bool"),
            validate=dict(required=False, type="str"),
        ),
        add_file_common_args=True,
    )

    changed = False
    path_hash = None
    dest_hash = None
    src = module.params["src"]
    dest = module.params["dest"]
    backup = module.params["backup"]
    delimiter = module.params["delimiter"]
    regexp = module.params["regexp"]
    compiled_regexp = None
    ignore_hidden = module.params["ignore_hidden"]
    validate = module.params.get("validate", None)

    result = dict(src=src, dest=dest)
    if not os.path.exists(src):
        module.fail_json(msg="Source (%s) does not exist" % src)

    if not os.path.isdir(src):
        module.fail_json(msg="Source (%s) is not a directory" % src)

    if regexp is not None:
        try:
            compiled_regexp = re.compile(regexp)
        except re.error as e:
            module.fail_json(msg='Invalid Regexp (%s) in "%s"' % (to_native(e), regexp))

    if validate and "%s" not in validate:
        module.fail_json(msg="validate must contain %%s: %s" % validate)

    path = assemble_from_fragments(
        src, delimiter, compiled_regexp, ignore_hidden, module.tmpdir
    )
    path_hash = module.sha1(path)
    result["checksum"] = path_hash

    # Backwards compat.  This won't return data if FIPS mode is active
    try:
        pathmd5 = module.md5(path)
    except ValueError:
        pathmd5 = None
    result["md5sum"] = pathmd5

    if os.path.exists(dest):
        dest_hash = module.sha1(dest)

    if path_hash != dest_hash:
        if validate:
            (rc, out, err) = module.run_command(validate % path)
            result["validation"] = dict(rc=rc, stdout=out, stderr=err)
            if rc != 0:
                cleanup(path)
                module.fail_json(msg="failed to validate: rc:%s error:%s" % (rc, err))
        if backup and dest_hash is not None:
            result["backup_file"] = module.backup_local(dest)

        module.atomic_move(path, dest, unsafe_writes=module.params["unsafe_writes"])
        changed = True

    cleanup(path, result)

    # handle file permissions
    file_args = module.load_file_common_arguments(module.params)
    result["changed"] = module.set_fs_attributes_if_different(file_args, changed)

    # Mission complete
    result["msg"] = "OK"
    module.exit_json(**result)