Debian Codegraph @

ansible_collections/community/sops/plugins/vars/sops.py

raw
1 # Copyright (c) 2018 Edoardo Tenani <[email protected]> (@endorama)
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 from __future__ import annotations
6
7 DOCUMENTATION = r"""
8 name: sops
9 author: Edoardo Tenani (@endorama) <[email protected]>
10 short_description: Loading SOPS-encrypted vars files
11 version_added: '0.1.0'
12 description:
13 - Load encrypted YAML files into corresponding groups/hosts in C(group_vars/) and C(host_vars/) directories.
14 - Files are encrypted prior to reading, making this plugin an effective companion to P(ansible.builtin.host_group_vars#vars)
15 plugin.
16 - Files are restricted to V(.sops.yaml), V(.sops.yml), V(.sops.json) extensions, unless configured otherwise with O(valid_extensions).
17 - Hidden files are ignored.
18 options:
19 valid_extensions:
20 default: [".sops.yml", ".sops.yaml", ".sops.json"]
21 description:
22 - Check all of these extensions when looking for 'variable' files.
23 - These files must be SOPS encrypted YAML or JSON files.
24 - By default the plugin will produce errors when encountering files matching these extensions that are not SOPS encrypted.
25 This behavior can be controlled with the O(handle_unencrypted_files) option.
26 type: list
27 elements: string
28 ini:
29 - key: valid_extensions
30 section: community.sops
31 version_added: 1.7.0
32 env:
33 - name: ANSIBLE_VARS_SOPS_PLUGIN_VALID_EXTENSIONS
34 version_added: 1.7.0
35 stage:
36 version_added: 0.2.0
37 ini:
38 - key: vars_stage
39 section: community.sops
40 env:
41 - name: ANSIBLE_VARS_SOPS_PLUGIN_STAGE
42 cache:
43 description:
44 - Whether to cache decrypted files or not.
45 - If the cache is disabled, the files will be decrypted for almost every task. This is very slow!
46 - Only disable caching if you modify the variable files during a playbook run and want the updated result to be available
47 from the next task on.
48 - 'Note that setting O(stage=inventory) has the same effect as setting O(cache=true): the variables will be loaded only
49 once (during inventory loading) and the vars plugin will not be called for every task.'
50 type: bool
51 default: true
52 version_added: 0.2.0
53 ini:
54 - key: vars_cache
55 section: community.sops
56 env:
57 - name: ANSIBLE_VARS_SOPS_PLUGIN_CACHE
58 disable_vars_plugin_temporarily:
59 description:
60 - Temporarily disable this plugin.
61 - Useful if ansible-inventory is supposed to be run without decrypting secrets (in AWX for instance).
62 type: bool
63 default: false
64 version_added: 1.3.0
65 env:
66 - name: SOPS_ANSIBLE_AWX_DISABLE_VARS_PLUGIN_TEMPORARILY
67 handle_unencrypted_files:
68 description:
69 - How to handle files that match the extensions in O(valid_extensions) that are not SOPS encrypted.
70 - The default value V(error) will produce an error.
71 - The value V(skip) will simply skip these files. This requires SOPS 3.9.0 or later.
72 - The value V(warn) will skip these files and emit a warning. This requires SOPS 3.9.0 or later.
73 - B(Note) that this will not help if the store SOPS uses cannot parse the file, for example because it is no valid JSON/YAML/...
74 file despite its file extension. For extensions other than the default ones SOPS uses the binary store, which tries
75 to parse the file as JSON.
76 type: string
77 choices:
78 - skip
79 - warn
80 - error
81 default: error
82 version_added: 1.8.0
83 ini:
84 - key: handle_unencrypted_files
85 section: community.sops
86 env:
87 - name: ANSIBLE_VARS_SOPS_PLUGIN_HANDLE_UNENCRYPTED_FILES
88 extends_documentation_fragment:
89 - ansible.builtin.vars_plugin_staging
90 - community.sops.sops.ansible_plugin # must come before community.sops.sops!
91 - community.sops.sops
92 - community.sops.sops.ansible_env
93 - community.sops.sops.ansible_ini
94 seealso:
95 - plugin: community.sops.sops
96 plugin_type: lookup
97 description: The sops lookup can be used decrypt SOPS-encrypted files.
98 - plugin: community.sops.decrypt
99 plugin_type: filter
100 description: The decrypt filter can be used to decrypt SOPS-encrypted in-memory data.
101 - module: community.sops.load_vars
102 """
103
104 import os
105 import typing as t
106 from collections.abc import Sequence, Mapping
107
108 from ansible.errors import AnsibleParserError
109 from ansible.inventory.host import Host
110 from ansible.inventory.group import Group
111 from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
112 from ansible.plugins.vars import BaseVarsPlugin
113 from ansible.utils.display import Display
114 from ansible.utils.vars import combine_vars
115 from ansible_collections.community.sops.plugins.module_utils.sops import Sops, SopsError
116 from ansible_collections.community.sops.plugins.plugin_utils._args import wrap_get_option_value_plugin_path
117
118 try:
119 from ansible.template import trust_as_template as _trust_as_template
120 HAS_DATATAGGING = True
121 except ImportError:
122 HAS_DATATAGGING = False
123
124
125 display = Display()
126
127 FOUND: dict[str, list[str]] = {}
128 DECRYPTED: dict[str, bytes] = {}
129
130
131 def _make_safe(value: t.Any) -> t.Any:
132 if isinstance(value, str):
133 # must come *before* Sequence, as strings are also instances of Sequence
134 if HAS_DATATAGGING and isinstance(value, str):
135 return _trust_as_template(value)
136 return value
137 if isinstance(value, Sequence):
138 return [_make_safe(v) for v in value]
139 if isinstance(value, Mapping):
140 return dict((k, _make_safe(v)) for k, v in value.items())
141 return value
142
143
144 class VarsModule(BaseVarsPlugin):
145
146 def get_vars(self, loader, path, entities, cache=None):
147 ''' parses the inventory file '''
148
149 if not isinstance(entities, list):
150 entities = [entities]
151
152 super().get_vars(loader, path, entities)
153
154 try:
155 sops_binary, sops_binary_origin = self.get_option_and_origin("sops_binary")
156 except AttributeError:
157 # Ansible-core 2.15 has no get_option_and_origin()!
158 sops_binary = self.get_option("sops_binary")
159 sops_binary_origin = "Direct"
160 get_option_value = wrap_get_option_value_plugin_path(
161 self.get_option,
162 sops_binary=sops_binary,
163 sops_binary_origin=sops_binary_origin,
164 )
165
166 if cache is None:
167 cache = self.get_option('cache')
168
169 if self.get_option('disable_vars_plugin_temporarily'):
170 return {}
171
172 valid_extensions = self.get_option('valid_extensions')
173 handle_unencrypted_files = self.get_option('handle_unencrypted_files')
174
175 data = {}
176 for entity in entities:
177 if isinstance(entity, Host):
178 subdir = 'host_vars'
179 elif isinstance(entity, Group):
180 subdir = 'group_vars'
181 else:
182 raise AnsibleParserError("Supplied entity must be Host or Group, got %s instead" % (type(entity)))
183
184 # avoid 'chroot' type inventory hostnames /path/to/chroot
185 if not entity.name.startswith(os.path.sep):
186 try:
187 found_files = []
188 # load vars
189 b_opath = os.path.realpath(to_bytes(os.path.join(self._basedir, subdir)))
190 opath = to_text(b_opath)
191 key = '%s.%s' % (entity.name, opath)
192 self._display.vvvv("key: %s" % (key))
193 if cache and key in FOUND:
194 found_files = FOUND[key]
195 else:
196 # no need to do much if path does not exist for basedir
197 if os.path.exists(b_opath):
198 if os.path.isdir(b_opath):
199 self._display.debug("\tprocessing dir %s" % opath)
200 # NOTE: iterating without extension allow retrieving files recursively
201 # A filter is then applied by iterating on all results and filtering by
202 # extension.
203 # See:
204 # - https://github.com/ansible-collections/community.sops/pull/6
205 found_files = loader.find_vars_files(opath, entity.name, extensions=valid_extensions, allow_dir=False)
206 found_files.extend([file_path for file_path in loader.find_vars_files(opath, entity.name)
207 if any(to_text(file_path).endswith(extension) for extension in valid_extensions)])
208 FOUND[key] = found_files
209 else:
210 self._display.warning("Found %s that is not a directory, skipping: %s" % (subdir, opath))
211
212 for found in found_files:
213 if cache and found in DECRYPTED:
214 file_content = DECRYPTED[found]
215 else:
216 sops_runner = Sops.get_sops_runner_from_options(get_option_value, display=display)
217 if handle_unencrypted_files != 'error' and not sops_runner.has_filestatus():
218 raise AnsibleParserError(
219 'Cannot use handle_unencrypted_files=%s with SOPS %s' % (handle_unencrypted_files, sops_runner.version_string)
220 )
221 try:
222 file_content = sops_runner.decrypt(found, get_option_value=get_option_value)
223 except SopsError as exc:
224 skip = False
225 if sops_runner.has_filestatus():
226 # Check whether sops thinks the file might be encrypted. If it thinks it is not,
227 # skip it. Otherwise, re-raise the original error
228 try:
229 file_status = sops_runner.get_filestatus(found)
230 if not file_status.encrypted:
231 if handle_unencrypted_files == 'skip':
232 self._display.vvvv("SOPS vars plugin: skipping unencrypted file %s" % found)
233 skip = True
234 elif handle_unencrypted_files == 'warn':
235 self._display.warning("SOPS vars plugin: skipping unencrypted file %s" % found)
236 skip = True
237 elif handle_unencrypted_files == 'error':
238 raise AnsibleParserError("SOPS vars plugin: file %s is not encrypted" % found)
239 except SopsError as status_exc:
240 # The filestatus operation can fail for example if sops cannot parse the file
241 # as JSON/YAML. In that case, also re-raise the original error
242 self._display.warning("SOPS vars plugin: cannot obtain file status of %s: %s" % (found, status_exc))
243 if skip:
244 continue
245 raise
246 DECRYPTED[found] = file_content
247 new_data = _make_safe(loader.load(file_content))
248 if new_data: # ignore empty files
249 data = combine_vars(data, new_data)
250
251 except AnsibleParserError:
252 raise
253 except SopsError as e:
254 raise AnsibleParserError(to_native(e))
255 except Exception as e:
256 raise AnsibleParserError('Unexpected error in the SOPS vars plugin: %s' % to_native(e))
257
258 return data