Debian Codegraph @

ansible_collections/community/general/plugins/lookup/shelvefile.py

raw
1 # Copyright (c) 2015, Alejandro Guirao <[email protected]>
2 # Copyright (c) 2012-17 Ansible Project
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5 from __future__ import annotations
6
7 DOCUMENTATION = r"""
8 name: shelvefile
9 author: Alejandro Guirao (!UNKNOWN) <[email protected]>
10 short_description: Read keys from Python shelve file
11 description:
12 - Read keys from Python shelve file.
13 options:
14 _terms:
15 description: Sets of key value pairs of parameters.
16 type: list
17 elements: str
18 key:
19 description: Key to query.
20 type: str
21 required: true
22 file:
23 description: Path to shelve file.
24 type: path
25 required: true
26 """
27
28 EXAMPLES = r"""
29 ---
30 - name: Retrieve a string value corresponding to a key inside a Python shelve file
31 ansible.builtin.debug:
32 msg: "{{ lookup('community.general.shelvefile', 'file=path_to_some_shelve_file.db key=key_to_retrieve') }}"
33 """
34
35 RETURN = r"""
36 _list:
37 description: Value(s) of key(s) in shelve file(s).
38 type: list
39 elements: str
40 """
41 import shelve
42
43 from ansible.errors import AnsibleAssertionError, AnsibleError
44 from ansible.module_utils.common.text.converters import to_bytes, to_text
45 from ansible.plugins.lookup import LookupBase
46
47 from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
48
49
50 class LookupModule(LookupBase):
51 def read_shelve(self, shelve_filename, key):
52 """
53 Read the value of "key" from a shelve file
54 """
55 d = shelve.open(to_bytes(shelve_filename))
56 res = d.get(key, None)
57 d.close()
58 return res
59
60 def run(self, terms, variables=None, **kwargs):
61 # TODO: use new-style option parsing
62 if not isinstance(terms, list):
63 terms = [terms]
64
65 check_for_wrong_terms(self, direct=kwargs)
66
67 ret = []
68
69 for term in terms:
70 paramvals = {"file": None, "key": None}
71 params = term.split()
72
73 try:
74 for param in params:
75 name, value = param.split("=")
76 if name not in paramvals:
77 raise AnsibleAssertionError(f"{name} not in paramvals")
78 paramvals[name] = value
79
80 except (ValueError, AssertionError) as e:
81 # In case "file" or "key" are not present
82 raise AnsibleError(e) from e
83
84 key = paramvals["key"]
85
86 # Search also in the role/files directory and in the playbook directory
87 shelvefile = self.find_file_in_search_path(variables, "files", paramvals["file"])
88
89 if shelvefile:
90 res = self.read_shelve(shelvefile, key)
91 if res is None:
92 raise AnsibleError(f"Key {key} not found in shelve file {shelvefile}")
93 # Convert the value read to string
94 ret.append(to_text(res))
95 break
96 else:
97 raise AnsibleError(f"Could not locate shelve file in lookup: {paramvals['file']}")
98
99 return ret