Debian Codegraph @

lib/ansible/plugins/action/template.py

raw
1 # Copyright: (c) 2015, Michael DeHaan <[email protected]>
2 # Copyright: (c) 2018, Ansible Project
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4
5 from __future__ import annotations
6
7 import os
8 import shutil
9 import stat
10 import tempfile
11
12 from jinja2.defaults import (
13 BLOCK_END_STRING,
14 BLOCK_START_STRING,
15 COMMENT_END_STRING,
16 COMMENT_START_STRING,
17 VARIABLE_END_STRING,
18 VARIABLE_START_STRING,
19 )
20
21 from ansible import constants as C
22 from ansible.config.manager import ensure_type
23 from ansible.errors import AnsibleError, AnsibleActionFail, AnsibleFileNotFound
24 from ansible.module_utils.common.text.converters import to_bytes, to_text, to_native
25 from ansible.module_utils.parsing.convert_bool import boolean
26 from ansible.plugins.action import ActionBase
27 from ansible.template import trust_as_template
28 from ansible._internal._templating import _template_vars
29
30
31 class ActionModule(ActionBase):
32
33 TRANSFERS_FILES = True
34 DEFAULT_NEWLINE_SEQUENCE = "\n"
35
36 def run(self, tmp=None, task_vars=None):
37 """ handler for template operations """
38
39 if task_vars is None:
40 task_vars = dict()
41
42 super(ActionModule, self).run(tmp, task_vars)
43 del tmp # tmp no longer has any effect
44
45 # Options type validation
46 # strings
47 for s_type in ('src', 'dest', 'state', 'newline_sequence', 'variable_start_string', 'variable_end_string', 'block_start_string',
48 'block_end_string', 'comment_start_string', 'comment_end_string'):
49 if s_type in self._task.args:
50 value = ensure_type(self._task.args[s_type], 'string')
51 if value is not None and not isinstance(value, str):
52 raise AnsibleActionFail("%s is expected to be a string, but got %s instead" % (s_type, type(value)))
53 self._task.args[s_type] = value
54
55 # booleans
56 try:
57 follow = boolean(self._task.args.get('follow', False), strict=False)
58 trim_blocks = boolean(self._task.args.get('trim_blocks', True), strict=False)
59 lstrip_blocks = boolean(self._task.args.get('lstrip_blocks', False), strict=False)
60 except TypeError as e:
61 raise AnsibleActionFail(to_native(e))
62
63 # assign to local vars for ease of use
64 source = self._task.args.get('src', None)
65 dest = self._task.args.get('dest', None)
66 state = self._task.args.get('state', None)
67 newline_sequence = self._task.args.get('newline_sequence', self.DEFAULT_NEWLINE_SEQUENCE)
68 variable_start_string = self._task.args.get('variable_start_string', VARIABLE_START_STRING)
69 variable_end_string = self._task.args.get('variable_end_string', VARIABLE_END_STRING)
70 block_start_string = self._task.args.get('block_start_string', BLOCK_START_STRING)
71 block_end_string = self._task.args.get('block_end_string', BLOCK_END_STRING)
72 comment_start_string = self._task.args.get('comment_start_string', COMMENT_START_STRING)
73 comment_end_string = self._task.args.get('comment_end_string', COMMENT_END_STRING)
74 output_encoding = self._task.args.get('output_encoding', 'utf-8') or 'utf-8'
75
76 wrong_sequences = ["\\n", "\\r", "\\r\\n"]
77 allowed_sequences = ["\n", "\r", "\r\n"]
78
79 # We need to convert unescaped sequences to proper escaped sequences for Jinja2
80 if newline_sequence in wrong_sequences:
81 newline_sequence = allowed_sequences[wrong_sequences.index(newline_sequence)]
82
83 try:
84 # logical validation
85 if state is not None:
86 raise AnsibleActionFail("'state' cannot be specified on a template")
87 elif source is None or dest is None:
88 raise AnsibleActionFail("src and dest are required")
89 elif newline_sequence not in allowed_sequences:
90 raise AnsibleActionFail("newline_sequence needs to be one of: \n, \r or \r\n")
91 else:
92 try:
93 source = self._find_needle('templates', source)
94 except AnsibleError as e:
95 return {"failed": True, "msg": to_text(e), "changed": False}
96
97 mode = self._task.args.get('mode', None)
98 if mode == 'preserve':
99 mode = '0%03o' % stat.S_IMODE(os.stat(source).st_mode)
100
101 # template the source data locally & get ready to transfer
102 try:
103 template_data = trust_as_template(self._loader.get_text_file_contents(source))
104 except AnsibleFileNotFound as e:
105 return {"failed": True, "msg": f"could not find src={source}: {e!r}", "changed": False}
106
107 # set jinja2 internal search path for includes
108 searchpath = task_vars.get('ansible_search_path', [])
109 searchpath.extend([self._loader._basedir, os.path.dirname(source)])
110
111 # We want to search into the 'templates' subdir of each search path in
112 # addition to our original search paths.
113 newsearchpath = []
114 for p in searchpath:
115 newsearchpath.append(os.path.join(p, 'templates'))
116 newsearchpath.append(p)
117 searchpath = newsearchpath
118
119 # add ansible 'template' vars
120 temp_vars = task_vars.copy()
121 temp_vars.update(_template_vars.generate_ansible_template_vars(
122 path=self._task.args.get('src', None),
123 fullpath=source,
124 dest_path=dest,
125 include_ansible_managed='ansible_managed' not in temp_vars, # do not clobber ansible_managed when set by the user
126 ))
127
128 overrides = dict(
129 block_start_string=block_start_string,
130 block_end_string=block_end_string,
131 variable_start_string=variable_start_string,
132 variable_end_string=variable_end_string,
133 comment_start_string=comment_start_string,
134 comment_end_string=comment_end_string,
135 trim_blocks=trim_blocks,
136 lstrip_blocks=lstrip_blocks,
137 newline_sequence=newline_sequence,
138 )
139
140 data_templar = self._templar.copy_with_new_env(searchpath=searchpath, available_variables=temp_vars)
141 resultant = data_templar.template(template_data, escape_backslashes=False, overrides=overrides)
142
143 if resultant is None:
144 resultant = ''
145
146 new_task = self._task.copy()
147 # mode is either the mode from task.args or the mode of the source file if the task.args
148 # mode == 'preserve'
149 new_task.args['mode'] = mode
150
151 # remove 'template only' options:
152 for remove in ('newline_sequence', 'block_start_string', 'block_end_string', 'variable_start_string', 'variable_end_string',
153 'comment_start_string', 'comment_end_string', 'trim_blocks', 'lstrip_blocks', 'output_encoding'):
154 new_task.args.pop(remove, None)
155
156 local_tempdir = tempfile.mkdtemp(dir=C.DEFAULT_LOCAL_TMP)
157
158 try:
159 result_file = os.path.join(local_tempdir, os.path.basename(source))
160 with open(to_bytes(result_file, errors='surrogate_or_strict'), 'wb') as f:
161 f.write(to_bytes(resultant, encoding=output_encoding, errors='surrogate_or_strict'))
162
163 new_task.args.update(
164 dict(
165 src=result_file,
166 dest=dest,
167 follow=follow,
168 ),
169 )
170 # call with ansible.legacy prefix to eliminate collisions with collections while still allowing local override
171 copy_action = self._shared_loader_obj.action_loader.get('ansible.legacy.copy',
172 task=new_task,
173 connection=self._connection,
174 play_context=self._play_context,
175 loader=self._loader,
176 templar=self._templar,
177 shared_loader_obj=self._shared_loader_obj)
178 return copy_action.run(task_vars=task_vars)
179 finally:
180 shutil.rmtree(to_bytes(local_tempdir, errors='surrogate_or_strict'))
181 finally:
182 self._remove_tmp_path(self._connection._shell.tmpdir)