Debian Codegraph @

lib/ansible/_internal/_templating/_template_vars.py

raw
1 from __future__ import annotations as _annotations
2
3 import datetime as _datetime
4 import os as _os
5 import pwd as _pwd
6 import time as _time
7
8 from ansible import constants as _constants
9 from ansible.module_utils._internal import _datatag
10
11
12 def generate_ansible_template_vars(
13 path: str,
14 fullpath: str | None = None,
15 dest_path: str | None = None,
16 include_ansible_managed: bool = True,
17 ) -> dict[str, object]:
18 """
19 Generate and return a dictionary with variable metadata about the template specified by `fullpath`.
20 If `fullpath` is `None`, `path` will be used instead.
21 """
22 # deprecated: description="update the ansible.windows collection to inline this logic instead of calling this internal function" core_version="2.23"
23 if fullpath is None:
24 fullpath = _os.path.abspath(path)
25
26 template_path = fullpath
27 template_stat = _os.stat(template_path)
28
29 template_uid: int | str
30
31 try:
32 template_uid = _pwd.getpwuid(template_stat.st_uid).pw_name
33 except KeyError:
34 template_uid = template_stat.st_uid
35
36 temp_vars = dict(
37 template_host=_os.uname()[1],
38 template_path=path,
39 template_mtime=_datetime.datetime.fromtimestamp(template_stat.st_mtime),
40 template_uid=template_uid,
41 template_run_date=_datetime.datetime.now(),
42 template_destpath=dest_path,
43 template_fullpath=fullpath,
44 )
45
46 if include_ansible_managed: # only inject the config default value if the variable wasn't set
47 temp_vars['ansible_managed'] = _generate_ansible_managed(template_stat)
48
49 return temp_vars
50
51
52 def _generate_ansible_managed(template_stat: _os.stat_result) -> str:
53 """Generate and return the `ansible_managed` variable."""
54 # deprecated: description="remove the `_generate_ansible_managed` function and use a constant instead" core_version="2.23"
55
56 from ansible.template import trust_as_template
57
58 managed_default = _constants.config.get_config_value('DEFAULT_MANAGED_STR')
59
60 managed_str = managed_default.format(
61 # IMPORTANT: These values must be constant strings to avoid template injection.
62 # Use Jinja template expressions where variables are needed.
63 host="{{ template_host }}",
64 uid="{{ template_uid }}",
65 file="{{ template_path }}",
66 )
67
68 ansible_managed = _time.strftime(managed_str, _time.localtime(template_stat.st_mtime))
69 ansible_managed = _datatag.AnsibleTagHelper.tag_copy(managed_default, ansible_managed)
70 ansible_managed = trust_as_template(ansible_managed)
71
72 return ansible_managed