Repository: ansible/ansible

Issue:
/tmp directory being used
<!---
Verify first that your issue/request is not already reported on GitHub.
Also test if the latest release, and master branch are affected too.
-->

##### ISSUE TYPE
<!--- Pick one below and delete the rest -->
 - Bug Report

##### COMPONENT NAME
<!---
Name of the module, plugin, task or feature
Do not include extra details here, e.g. "vyos_command" not "the network module vyos_command" or the full path
-->
template and potentially more

##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes below -->
```
$ ansible --version
ansible 2.2.1.0
  config file = /opt/****/ansible.cfg
  configured module search path = [ '/home/****/ansible']
```

##### CONFIGURATION
<!---
If using Ansible 2.4 or above, paste the results of "ansible-config dump --only-changed"
Otherwise, mention any settings you have changed/added/removed in ansible.cfg
(or using the ANSIBLE_* environment variables).
-->
```
$ cat ansible.cfg | grep tmp
local_tmp = /opt/***/.ansible/tmp
remote_tmp = /opt/***/.ansible/tmp
$

```
##### OS / ENVIRONMENT
<!---
Mention the OS you are running Ansible from, and the OS you are
managing, or say "N/A" for anything that is not platform-specific.
Also mention the specific version of what you are trying to control,
e.g. if this is a network bug the version of firmware on the network device.
-->
```
$ cat /etc/os-release
NAME="Red Hat Enterprise Linux Server"
VERSION="7.3 (Maipo)"
ID="rhel"
ID_LIKE="fedora"
VERSION_ID="7.3"
PRETTY_NAME="Red Hat Enterprise Linux"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:redhat:enterprise_linux:7.3:GA:server"
HOME_URL="https://www.redhat.com/"
BUG_REPORT_URL="https://bugzilla.redhat.com/"

REDHAT_BUGZILLA_PRODUCT="Red Hat Enterprise Linux 7"
REDHAT_BUGZILLA_PRODUCT_VERSION=7.3
REDHAT_SUPPORT_PRODUCT="Red Hat Enterprise Linux"
REDHAT_SUPPORT_PRODUCT_VERSION="7.3"

```
##### SUMMARY
<!--- Explain the problem briefly -->
Files are writing to /tmp when remote_tmp and local_tmp is defined

##### STEPS TO REPRODUCE
<!---
For bugs, show exactly how to reproduce the problem, using a minimal test-case.
For new features, show how the feature would be used.
-->

<!--- Paste example playbooks or commands between quotes below -->


```yaml

    - name: "{{ site }} - GENERATE JSON REPORT PER SITE STATS ONLY"
      template:
        src: "{{ role_path }}/templates/reports/sites/partial_table.j2"
        dest: '{{ output_dir }}/reports/html/partial/{{ site }}.partial'
```

<!--- You can also paste gist.github.com links for larger files -->

##### EXPECTED RESULTS
<!--- What did you expect to happen when running the steps above? -->
```
localhost                  : ok=360  changed=29   unreachable=0    failed=0
```
##### ACTUAL RESULTS
<!--- What actually happened? If possible run with extra verbosity (-vvvv) -->

<!--- Paste verbatim command output between quotes below -->
```
TASK [reports : *** - GENERATE JSON REPORT PER SITE STATS ONLY] ****************
fatal: [localhost]: FAILED! => {"changed": false, "failed": true, "msg": "[Errno 13] Permission denied: '/tmp/tmpuv61yn'"}

PLAY RECAP *********************************************************************
localhost                  : ok=360  changed=29   unreachable=0    failed=1
```




Discussion:
Files identified in the description:
* [lib/ansible/modules/files/template.py](https://github.com/ansible/ansible/blob/devel/lib/ansible/modules/files/template.py)

If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command.

[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)
<!--- boilerplate: components_banner --->
I cannot duplicate this, and your selection from `ansible.cfg` doesn't indicate the header it is nested under.

It is also not clear if you have indicated that the task is suppose to run with `become`.

I also notice you are using an older version of ansible, the current stable version is 2.4.2.  Is there the possibility you could test this scenario with a newer version?

needs_info
Fair enough about header, will grab relavant information. Not meant to use become, no reason to. Ansible is on client network and don’t have much I can change without justification, but will look to replicate on my own systems.


No real way via text to show, but I can see that this is in fact true as of 2.4.2 as well. 

You can see it is writing files to the ansible.cfg defined remote_tmp or local_tmp, in addition to /tmp. Should be easy to replicate in any environment. 


Showing files writing to two different places
```
(ansible2.4) ken@ken-VirtualBox:/tmp$ ls
tmpBDxUw1  tmpJ0zToE  tmpkZrCT4  tmpmXFiwo  tmpWeC3Dc
(ansible2.4) ken@ken-VirtualBox:/tmp$ ls
ansible_DrNWly  tmp9qXpOT  tmpJ0zToE  tmpkZrCT4  tmpmXFiwo  tmpWeC3Dc
(ansible2.4) ken@ken-VirtualBox:/tmp$ ls
tmpJ0zToE  tmpkZrCT4  tmpmXFiwo  tmpWeC3Dc
(ansible2.4) ken@ken-VirtualBox:/tmp$ ls ~/github/cookbook/.tmp/
(ansible2.4) ken@ken-VirtualBox:/tmp$ ls ~/github/cookbook/.tmp/
ansible-local-23676j_A0F7  ansible-tmp-1516151869.94-252041768114446
(ansible2.4) ken@ken-VirtualBox:/tmp$
```


Showing ansible.cfg file, playbook, and version. 
```
(ansible2.4) ken@ken-VirtualBox:~/github/cookbook$ pwd
/home/ken/github/cookbook
(ansible2.4) ken@ken-VirtualBox:~/github/cookbook$ cat ansible.cfg
[defaults]

remote_tmp     = /home/ken/github/cookbook/.tmp
local_tmp      = /home/ken/github/cookbook/.tmp
(ansible2.4) ken@ken-VirtualBox:~/github/cookbook$ cat jinja.yml
---

  - name: CREATE CONFIG FILE
    hosts: all
    gather_facts: no
    connection: local

    #vars_files:
    #  - vars/global_settings.yml
    vars:
      ntp:
        source_interface: 'loopback0'
        prefer: '10.10.10.10'
        servers:
          - '10.10.10.11'
          - '10.10.10.12'
          - '10.10.10.13'
      users:
        ken:
          level: 10
    #      password: '123123123123'

    tasks:
    #  - debug: var=hostvars
      - name: BUILD JINJA CONFIGS
        template:
          src: "templates/fileglob/{{ item | basename }}"
          dest: 'files/jinja/{{ item | basename | regex_replace("\.j2","") }}.cfg'
        with_fileglob:
          - "templates/fileglob/*"
(ansible2.4) ken@ken-VirtualBox:~/github/cookbook$ ansible --version
ansible 2.4.1.0
  config file = /home/ken/github/cookbook/ansible.cfg
  configured module search path = [u'/home/ken/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /home/ken/.virtualenvs/ansible2.4/local/lib/python2.7/site-packages/ansible
  executable location = /home/ken/.virtualenvs/ansible2.4/bin/ansible
  python version = 2.7.6 (default, Oct 26 2016, 20:32:47) [GCC 4.8.4]
(ansible2.4) ken@ken-VirtualBox:~/github/cookbook$
```

Resolving patch:
diff --git a/lib/ansible/plugins/action/template.py b/lib/ansible/plugins/action/template.py
--- a/lib/ansible/plugins/action/template.py
+++ b/lib/ansible/plugins/action/template.py
@@ -21,6 +21,7 @@
 import shutil
 import tempfile
 
+from ansible import constants as C
 from ansible.errors import AnsibleError, AnsibleFileNotFound, AnsibleAction, AnsibleActionFail
 from ansible.module_utils._text import to_bytes, to_text
 from ansible.module_utils.parsing.convert_bool import boolean
@@ -132,7 +133,7 @@ def run(self, tmp=None, task_vars=None):
             new_task.args.pop('variable_end_string', None)
             new_task.args.pop('trim_blocks', None)
             try:
-                tempdir = tempfile.mkdtemp()
+                tempdir = tempfile.mkdtemp(dir=C.DEFAULT_LOCAL_TMP)
                 result_file = os.path.join(tempdir, os.path.basename(source))
                 with open(result_file, 'wb') as f:
                     f.write(to_bytes(resultant, errors='surrogate_or_strict'))


Test patch: