Cleanup temporary files after content argument usage

When using content: the config_template module will create a
temporary file. This patch ensures a deterministic path to the
temp file is used, and removes it at the end of the module
execution.

Change-Id: I3b3354178ba1a2b9c95decb3d3e0c9a1c2689056
This commit is contained in:
Jean-Philippe Evrard 2016-12-21 13:56:59 +00:00
parent bc9e947f9b
commit 6d76bfe7df

View File

@ -31,6 +31,7 @@ import pwd
import re import re
import time import time
import yaml import yaml
import tempfile as tmpfilelib
from ansible.plugins.action import ActionBase from ansible.plugins.action import ActionBase
@ -427,7 +428,7 @@ class ActionModule(ActionBase):
file_path = self._loader.get_basedir() file_path = self._loader.get_basedir()
user_source = self._task.args.get('src') user_source = self._task.args.get('src')
user_content = self._task.args.get('content') user_content = str(self._task.args.get('content'))
if not user_source: if not user_source:
if not user_content: if not user_content:
return False, dict( return False, dict(
@ -436,21 +437,20 @@ class ActionModule(ActionBase):
) )
else: else:
tmp_content = None tmp_content = None
fd, tmp_content = tmpfilelib.mkstemp()
try: try:
remote_user = task_vars.get('ansible_user') or self._play_context.remote_user with open(tmp_content, 'wb') as f:
if not tmp_content: f.write(user_content.encode())
tmp_content = self._make_tmp_path(remote_user) + 'content' except Exception as err:
except TypeError: os.remove(tmp_content)
if not tmp_content: raise Exception(err)
tmp_content = self._make_tmp_path() + 'content' self._task.args['src'] = source = tmp_content
with open(tmp_content, 'w') as f: else:
f.writelines(user_content) source = self._loader.path_dwim_relative(
user_source = tmp_content file_path,
source = self._loader.path_dwim_relative( 'templates',
file_path, user_source
'templates', )
user_source
)
searchpath.insert(1, os.path.dirname(source)) searchpath.insert(1, os.path.dirname(source))
_dest = self._task.args.get('dest') _dest = self._task.args.get('dest')
@ -577,10 +577,15 @@ class ActionModule(ActionBase):
new_module_args.pop('config_overrides', None) new_module_args.pop('config_overrides', None)
new_module_args.pop('config_type', None) new_module_args.pop('config_type', None)
new_module_args.pop('list_extend', None) new_module_args.pop('list_extend', None)
# Content from config_template is converted to src
new_module_args.pop('content', None)
# Run the copy module # Run the copy module
return self._execute_module( rc = self._execute_module(
module_name='copy', module_name='copy',
module_args=new_module_args, module_args=new_module_args,
task_vars=task_vars task_vars=task_vars
) )
if self._task.args.get('content'):
os.remove(_vars['source'])
return rc