Debian Codegraph @

ansible_collections/community/sops/plugins/lookup/sops.py

raw
1 # Copyright 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: Read SOPS-encrypted file contents
11 version_added: '0.1.0'
12 description:
13 - This lookup returns the contents from a file on the Ansible controller's file system.
14 - This lookup requires the C(sops) executable to be available in the controller PATH.
15 options:
16 _terms:
17 description: Path(s) of files to read.
18 required: true
19 type: list
20 elements: str
21 rstrip:
22 description: Whether to remove trailing newlines and spaces.
23 type: bool
24 default: true
25 base64:
26 description:
27 - Base64-encodes the parsed result.
28 - Use this if you want to store binary data in Ansible variables.
29 type: bool
30 default: false
31 input_type:
32 description:
33 - Tell SOPS how to interpret the encrypted file.
34 - By default, SOPS will chose the input type from the file extension. If it detects the wrong type for a file, this
35 could result in decryption failing.
36 - The value V(ini) is available since community.sops 1.9.0.
37 type: str
38 choices:
39 - binary
40 - json
41 - yaml
42 - dotenv
43 - ini
44 output_type:
45 description:
46 - Tell SOPS how to interpret the decrypted file.
47 - By default, SOPS will chose the output type from the file extension. If it detects the wrong type for a file, this
48 could result in decryption failing.
49 - The value V(ini) is available since community.sops 1.9.0.
50 type: str
51 choices:
52 - binary
53 - json
54 - yaml
55 - dotenv
56 - ini
57 empty_on_not_exist:
58 description:
59 - When set to V(true), will not raise an error when a file cannot be found, but return an empty string instead.
60 type: bool
61 default: false
62 extract:
63 description:
64 - Tell SOPS to extract a specific key from a JSON or YAML file.
65 - Expects a string with the same 'querystring' syntax as SOPS' C(--encrypt) option, for example V(["somekey"][0]).
66 - B(Note:) Escape quotes appropriately.
67 type: str
68 version_added: 1.9.0
69 extends_documentation_fragment:
70 - community.sops.sops.ansible_plugin # must come before community.sops.sops!
71 - community.sops.sops
72 - community.sops.sops.ansible_variables
73 - community.sops.sops.ansible_env
74 - community.sops.sops.ansible_ini
75 notes:
76 - This lookup does not understand 'globbing' - use the P(ansible.builtin.fileglob#lookup) lookup instead.
77 seealso:
78 - plugin: community.sops.decrypt
79 plugin_type: filter
80 description: The decrypt filter can be used to descrypt SOPS-encrypted in-memory data.
81 - plugin: community.sops.sops
82 plugin_type: vars
83 description: The sops vars plugin can be used to load SOPS-encrypted host or group variables.
84 - module: community.sops.load_vars
85 """
86
87 EXAMPLES = r"""
88 ---
89 - name: Output secrets to screen (BAD IDEA!)
90 ansible.builtin.debug:
91 msg: "Content: {{ lookup('community.sops.sops', item) }}"
92 loop:
93 - sops-encrypted-file.enc.yaml
94
95 - name: Add SSH private key
96 ansible.builtin.copy:
97 # Note that rstrip=false is necessary for some SSH versions to be able to use the key
98 content: "{{ lookup('community.sops.sops', user + '-id_rsa', rstrip=false) }}"
99 dest: /home/{{ user }}/.ssh/id_rsa
100 owner: "{{ user }}"
101 group: "{{ user }}"
102 mode: "0600"
103 no_log: true # avoid content to be written to log
104
105 - name: The file file.json is a YAML file, which contains the encryption of binary data
106 ansible.builtin.debug:
107 msg: "Content: {{ lookup('community.sops.sops', 'file.json', input_type='yaml', output_type='binary') }}"
108 """
109
110 RETURN = r"""
111 _raw:
112 description: Decrypted file content.
113 type: list
114 elements: str
115 """
116
117 import base64
118
119 from ansible.errors import AnsibleLookupError
120 from ansible.module_utils.common.text.converters import to_native
121 from ansible.module_utils.compat.version import LooseVersion
122 from ansible.plugins.lookup import LookupBase
123 from ansible.release import __version__ as ansible_version
124 from ansible_collections.community.sops.plugins.module_utils.sops import Sops, SopsError
125 from ansible_collections.community.sops.plugins.plugin_utils._args import wrap_get_option_value_plugin_path
126
127 from ansible.utils.display import Display
128 display = Display()
129
130
131 class LookupModule(LookupBase):
132
133 def run(self, terms, variables=None, **kwargs):
134 self.set_options(var_options=variables, direct=kwargs)
135 rstrip = self.get_option('rstrip')
136 use_base64 = self.get_option('base64')
137 input_type = self.get_option('input_type')
138 output_type = self.get_option('output_type')
139 empty_on_not_exist = self.get_option('empty_on_not_exist')
140 extract = self.get_option('extract')
141
142 ret = []
143
144 try:
145 sops_binary, sops_binary_origin = self.get_option_and_origin("sops_binary")
146 if sops_binary is None and (
147 LooseVersion(ansible_version) < LooseVersion("2.18.8")
148 or
149 LooseVersion(ansible_version) == LooseVersion("2.19.0")
150 ):
151 # Ansible-core < 2.18.8 and 2.19.0 are broken: https://github.com/ansible/ansible/issues/85480
152 sops_binary = self.get_option("sops_binary")
153 sops_binary_origin = "Direct"
154 except AttributeError:
155 # Ansible-core 2.15 has no get_option_and_origin()!
156 sops_binary = self.get_option("sops_binary")
157 sops_binary_origin = "Direct"
158 get_option_value = wrap_get_option_value_plugin_path(
159 self.get_option,
160 sops_binary=sops_binary,
161 sops_binary_origin=sops_binary_origin,
162 )
163
164 for term in terms:
165 display.debug("Sops lookup term: %s" % term)
166 lookupfile = self.find_file_in_search_path(variables, 'files', term, ignore_missing=empty_on_not_exist)
167 display.vvvv(u"Sops lookup using %s as file" % lookupfile)
168
169 if not lookupfile:
170 if empty_on_not_exist:
171 ret.append('')
172 continue
173 raise AnsibleLookupError("could not locate file in lookup: %s" % to_native(term))
174
175 try:
176 output = Sops.decrypt(
177 lookupfile, display=display, rstrip=rstrip, decode_output=(not use_base64),
178 input_type=input_type, output_type=output_type, get_option_value=get_option_value, extract=extract)
179 except SopsError as e:
180 raise AnsibleLookupError(to_native(e))
181
182 if use_base64:
183 output = to_native(base64.b64encode(output))
184
185 ret.append(output)
186
187 return ret