Debian Codegraph @

ansible_collections/community/sops/plugins/modules/sops_encrypt.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (c) 2020, Felix Fontein <[email protected]>
5 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
6 # SPDX-License-Identifier: GPL-3.0-or-later
7
8 from __future__ import absolute_import, division, print_function
9 __metaclass__ = type
10
11
12 DOCUMENTATION = r"""
13 author: Felix Fontein (@felixfontein)
14 module: sops_encrypt
15 short_description: Encrypt data with SOPS
16 version_added: '0.1.0'
17 description:
18 - Allows to encrypt binary data (Base64 encoded), text data, JSON or YAML data with SOPS.
19 options:
20 path:
21 description:
22 - The SOPS encrypt file.
23 type: path
24 required: true
25 force:
26 description:
27 - Force rewriting the encrypted file.
28 type: bool
29 default: false
30 content_text:
31 description:
32 - The data to encrypt. Must be a Unicode text.
33 - Please note that the module might not be idempotent if the text can be parsed as JSON or YAML.
34 - Exactly one of O(content_text), O(content_binary), O(content_json), and O(content_yaml) must be specified.
35 type: str
36 content_binary:
37 description:
38 - The data to encrypt. Must be L(Base64 encoded,https://en.wikipedia.org/wiki/Base64) binary data.
39 - Please note that the module might not be idempotent if the data can be parsed as JSON or YAML.
40 - Exactly one of O(content_text), O(content_binary), O(content_json), and O(content_yaml) must be specified.
41 type: str
42 content_json:
43 description:
44 - The data to encrypt. Must be a JSON dictionary.
45 - Exactly one of O(content_text), O(content_binary), O(content_json), and O(content_yaml) must be specified.
46 type: dict
47 content_yaml:
48 description:
49 - The data to encrypt. Must be a YAML dictionary.
50 - Please note that Ansible only allows to pass data that can be represented as a JSON dictionary.
51 - Exactly one of O(content_text), O(content_binary), O(content_json), and O(content_yaml) must be specified.
52 type: dict
53 extends_documentation_fragment:
54 - ansible.builtin.files
55 - community.sops.sops
56 - community.sops.sops.encrypt_specific
57 - community.sops.attributes
58 - community.sops.attributes.files
59 attributes:
60 check_mode:
61 support: full
62 diff_mode:
63 support: none
64 safe_file_operations:
65 support: full
66 idempotent:
67 support: full
68 seealso:
69 - plugin: community.sops.sops
70 plugin_type: lookup
71 description: The sops lookup can be used decrypt SOPS-encrypted files.
72 """
73
74 EXAMPLES = r"""
75 ---
76 - name: Encrypt a secret text
77 community.sops.sops_encrypt:
78 path: text-data.sops
79 content_text: This is a secret text.
80
81 - name: Encrypt the contents of a file
82 community.sops.sops_encrypt:
83 path: binary-data.sops
84 content_binary: "{{ lookup('ansible.builtin.file', '/path/to/file', rstrip=false) | b64encode }}"
85
86 - name: Encrypt some datastructure as YAML
87 community.sops.sops_encrypt:
88 path: stuff.sops.yaml
89 content_yaml: "{{ result }}"
90 """
91
92 RETURN = r"""#"""
93
94
95 import base64
96 import json
97 import os
98 import traceback
99
100 from ansible.module_utils.basic import AnsibleModule, missing_required_lib
101 from ansible.module_utils.common.text.converters import to_text
102
103 from ansible_collections.community.sops.plugins.module_utils.io import write_file
104 from ansible_collections.community.sops.plugins.module_utils.sops import Sops, SopsError, get_sops_argument_spec
105
106 try:
107 import yaml
108 YAML_IMP_ERR = None
109 HAS_YAML = True
110 except ImportError:
111 YAML_IMP_ERR = traceback.format_exc()
112 HAS_YAML = False
113 yaml = None # type: ignore[assignment] # use better type later...
114
115
116 def get_data_type(module):
117 if module.params['content_text'] is not None:
118 return 'binary'
119 if module.params['content_binary'] is not None:
120 return 'binary'
121 if module.params['content_json'] is not None:
122 return 'json'
123 if module.params['content_yaml'] is not None:
124 return 'yaml'
125 module.fail_json(msg='Internal error: unknown content type') # pragma: no cover
126
127
128 def compare_encoded_content(module, binary_data, content):
129 if module.params['content_text'] is not None:
130 return content == module.params['content_text'].encode('utf-8')
131 if module.params['content_binary'] is not None:
132 return content == binary_data
133 if module.params['content_json'] is not None:
134 # Compare JSON
135 try:
136 return json.loads(content) == module.params['content_json']
137 except Exception:
138 # Treat parsing errors as content not equal
139 return False
140 if module.params['content_yaml'] is not None:
141 # Compare YAML
142 try:
143 return yaml.safe_load(content) == module.params['content_yaml']
144 except Exception:
145 # Treat parsing errors as content not equal
146 return False
147 module.fail_json(msg='Internal error: unknown content type') # pragma: no cover
148
149
150 def get_encoded_type_content(module, binary_data):
151 if module.params['content_text'] is not None:
152 return 'binary', module.params['content_text'].encode('utf-8')
153 if module.params['content_binary'] is not None:
154 return 'binary', binary_data
155 if module.params['content_json'] is not None:
156 return 'json', json.dumps(module.params['content_json']).encode('utf-8')
157 if module.params['content_yaml'] is not None:
158 return 'yaml', yaml.safe_dump(module.params['content_yaml']).encode('utf-8')
159 module.fail_json(msg='Internal error: unknown content type') # pragma: no cover
160
161
162 def main():
163 argument_spec = dict(
164 path=dict(type='path', required=True),
165 force=dict(type='bool', default=False),
166 content_text=dict(type='str', no_log=True),
167 content_binary=dict(type='str', no_log=True),
168 content_json=dict(type='dict', no_log=True),
169 content_yaml=dict(type='dict', no_log=True),
170 )
171 argument_spec.update(get_sops_argument_spec(add_encrypt_specific=True))
172 module = AnsibleModule(
173 argument_spec=argument_spec,
174 mutually_exclusive=[
175 ('content_text', 'content_binary', 'content_json', 'content_yaml'),
176 ],
177 required_one_of=[
178 ('content_text', 'content_binary', 'content_json', 'content_yaml'),
179 ],
180 supports_check_mode=True,
181 add_file_common_args=True,
182 )
183
184 # Check YAML
185 if module.params['content_yaml'] is not None and not HAS_YAML:
186 module.fail_json(msg=missing_required_lib('pyyaml'), exception=YAML_IMP_ERR)
187
188 # Decode binary data
189 binary_data = None
190 if module.params['content_binary'] is not None:
191 try:
192 binary_data = base64.b64decode(module.params['content_binary'])
193 except Exception as e:
194 module.fail_json(msg='Cannot decode Base64 encoded data: {0}'.format(e))
195
196 path = module.params['path']
197 directory = os.path.dirname(path) or None
198 changed = False
199
200 def get_option_value(argument_name):
201 return module.params.get(argument_name)
202
203 try:
204 if module.params['force'] or not os.path.exists(path):
205 # Simply encrypt
206 changed = True
207 else:
208 # Change detection: check if encrypted data equals new data
209 decrypted_content = Sops.decrypt(
210 path, decode_output=False, output_type=get_data_type(module), rstrip=False,
211 get_option_value=get_option_value, module=module,
212 )
213 if not compare_encoded_content(module, binary_data, decrypted_content):
214 changed = True
215
216 if changed and not module.check_mode:
217 input_type, input_data = get_encoded_type_content(module, binary_data)
218 output_type = None
219 if path.endswith('.json'):
220 output_type = 'json'
221 elif path.endswith(('.yml', '.yaml')):
222 output_type = 'yaml'
223 data = Sops.encrypt(
224 data=input_data, cwd=directory, input_type=input_type, output_type=output_type,
225 filename=os.path.relpath(path, directory) if directory is not None else path,
226 get_option_value=get_option_value, module=module,
227 )
228 write_file(module, data)
229 except SopsError as e:
230 module.fail_json(msg=to_text(e))
231
232 file_args = module.load_file_common_arguments(module.params)
233 changed = module.set_fs_attributes_if_different(file_args, changed)
234
235 module.exit_json(changed=changed)
236
237
238 if __name__ == '__main__':
239 main()