Debian Codegraph @

lib/ansible/plugins/lookup/file.py

raw
1 # (c) 2012, Daniel Hokka Zakrisson <[email protected]>
2 # (c) 2017 Ansible Project
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4 from __future__ import annotations
5
6 DOCUMENTATION = """
7 name: file
8 author: Daniel Hokka Zakrisson (!UNKNOWN) <[email protected]>
9 version_added: "0.9"
10 short_description: read file contents
11 description:
12 - This lookup returns the contents from a file on the Ansible controller's file system.
13 positional: _terms
14 options:
15 _terms:
16 description: path(s) of files to read
17 required: True
18 rstrip:
19 description: whether or not to remove whitespace from the ending of the looked-up file
20 type: bool
21 required: False
22 default: True
23 lstrip:
24 description: whether or not to remove whitespace from the beginning of the looked-up file
25 type: bool
26 required: False
27 default: False
28 notes:
29 - this lookup does not understand 'globbing', use the fileglob lookup instead.
30 seealso:
31 - ref: playbook_task_paths
32 description: Search paths used for relative files.
33 """
34
35 EXAMPLES = """
36 - ansible.builtin.debug:
37 msg: "the value of foo.txt is {{ lookup('ansible.builtin.file', '/etc/foo.txt') }}"
38
39 - name: display multiple file contents
40 ansible.builtin.debug: var=item
41 with_file:
42 - "/path/to/foo.txt"
43 - "bar.txt" # will be looked in files/ dir relative to play or in role
44 - "/path/to/biz.txt"
45 """
46
47 RETURN = """
48 _raw:
49 description:
50 - content of file(s)
51 type: list
52 elements: str
53 """
54
55 from ansible.errors import AnsibleError
56 from ansible.plugins.lookup import LookupBase
57 from ansible.utils.display import Display
58
59 display = Display()
60
61
62 class LookupModule(LookupBase):
63
64 def run(self, terms, variables=None, **kwargs):
65
66 ret = []
67 self.set_options(var_options=variables, direct=kwargs)
68
69 for term in terms:
70 display.debug("File lookup term: %s" % term)
71 # Find the file in the expected search path
72 try:
73 lookupfile = self.find_file_in_search_path(variables, 'files', term, ignore_missing=True)
74 display.vvvv(u"File lookup using %s as file" % lookupfile)
75 if lookupfile:
76 contents = self._loader.get_text_file_contents(lookupfile)
77 if self.get_option('lstrip'):
78 contents = contents.lstrip()
79 if self.get_option('rstrip'):
80 contents = contents.rstrip()
81 ret.append(contents)
82 else:
83 # TODO: only add search info if abs path?
84 raise AnsibleError("File not found. Use -vvvvv to see paths searched.")
85 except AnsibleError as ex:
86 raise AnsibleError(f"Unable to access the file {term!r}.") from ex
87
88 return ret