Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_ssl_key.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2017, F5 Networks Inc.
5 # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10 DOCUMENTATION = r'''
11 ---
12 module: bigip_ssl_key
13 short_description: Import/Delete SSL keys from BIG-IP
14 description:
15 - This module imports/deletes SSL keys on a BIG-IP. Keys can be imported
16 from key files on the local disk, in PEM format.
17 version_added: "1.0.0"
18 options:
19 content:
20 description:
21 - Sets the contents of a key directly to the specified value. This is
22 used with lookup plugins or for anything with formatting or templating.
23 This must be provided when C(state) is C(present).
24 type: str
25 aliases:
26 - key_content
27 state:
28 description:
29 - When C(present), ensures the key is uploaded to the device. When
30 C(absent), ensures the key is removed from the device. If the key
31 is currently in use, the module is not able to remove the key.
32 type: str
33 choices:
34 - present
35 - absent
36 default: present
37 name:
38 description:
39 - The name of the key.
40 type: str
41 required: True
42 true_names:
43 description:
44 - When C(true), the module does not append C(.key) extension to the given key name.
45 - When C(false), the module appends C(.key) extension to the given key name.
46 type: bool
47 default: false
48 version_added: "1.24.0"
49 passphrase:
50 description:
51 - Passphrase on key.
52 type: str
53 partition:
54 description:
55 - Device partition to manage resources on.
56 type: str
57 default: Common
58 notes:
59 - This module does not behave like other modules you might include in
60 roles, where referencing files or templates first looks in the role's
61 files or templates directory. To have the module behave that way, use
62 the Ansible file or template lookup (see Examples). The lookups behave
63 as expected in a role context.
64 extends_documentation_fragment: f5networks.f5_modules.f5
65 requirements:
66 - BIG-IP >= v12
67 author:
68 - Tim Rupp (@caphrim007)
69 - Wojciech Wypior (@wojtek0806)
70 '''
71
72 EXAMPLES = r'''
73 - name: Use a file lookup to import key
74 bigip_ssl_key:
75 name: key-name
76 state: present
77 content: "{{ lookup('file', '/path/to/key.key') }}"
78 provider:
79 server: lb.mydomain.com
80 user: admin
81 password: secret
82 delegate_to: localhost
83
84 - name: Delete key
85 bigip_ssl_key:
86 name: key-name
87 state: absent
88 provider:
89 server: lb.mydomain.com
90 user: admin
91 password: secret
92 delegate_to: localhost
93 '''
94
95 RETURN = r'''
96 key_filename:
97 description:
98 - The name of the SSL certificate key. The C(key_filename) and
99 C(cert_filename) will be similar to each other, however the
100 C(key_filename) will have a C(.key) extension.
101 returned: created
102 type: str
103 sample: cert1.key
104 key_checksum:
105 description: SHA1 checksum of the key.
106 returned: changed and created
107 type: str
108 sample: cf23df2207d99a74fbe169e3eba035e633b65d94
109 key_source_path:
110 description: Path on BIG-IP where the source of the key is stored.
111 returned: created
112 type: str
113 sample: /var/config/rest/downloads/cert1.key
114 '''
115
116 import hashlib
117 import os
118 import re
119 from datetime import datetime
120
121 from ansible.module_utils.basic import (
122 AnsibleModule, env_fallback
123 )
124
125 from ..module_utils.bigip import F5RestClient
126 from ..module_utils.common import (
127 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, flatten_boolean
128 )
129 from ..module_utils.icontrol import (
130 upload_file, tmos_version
131 )
132 from ..module_utils.teem import send_teem
133
134 try:
135 from StringIO import StringIO
136 except ImportError:
137 from io import StringIO
138
139
140 class Parameters(AnsibleF5Parameters):
141 download_path = '/var/config/rest/downloads'
142
143 api_map = {
144 'sourcePath': 'key_source_path'
145 }
146
147 updatables = [
148 'key_checksum',
149 'key_source_path',
150 ]
151
152 returnables = [
153 'key_filename',
154 'key_checksum',
155 'key_source_path',
156 ]
157
158 api_attributes = [
159 'passphrase',
160 'sourcePath',
161 ]
162
163
164 class ApiParameters(Parameters):
165 @property
166 def checksum(self):
167 if self._values['checksum'] is None:
168 return None
169 pattern = r'SHA1:\d+:(?P<value>[\w+]{40})'
170 matches = re.match(pattern, self._values['checksum'])
171 if matches:
172 return matches.group('value')
173 else:
174 return None
175
176
177 class ModuleParameters(Parameters):
178 def _get_hash(self, content):
179 k = hashlib.sha1()
180 s = StringIO(content)
181 while True:
182 data = s.read(1024)
183 if not data:
184 break
185 k.update(data.encode('utf-8'))
186 return k.hexdigest()
187
188 @property
189 def key_filename(self):
190 true_name = flatten_boolean(self.true_names)
191 if true_name == 'yes':
192 return self.name
193 else:
194 if self.name.endswith('.key'):
195 return self.name
196 else:
197 return self.name + '.key'
198
199 @property
200 def key_checksum(self):
201 if self.content is None:
202 return None
203 return self._get_hash(self.content)
204
205 @property
206 def key_source_path(self):
207 result = 'file://' + os.path.join(
208 self.download_path,
209 self.key_filename
210 )
211 return result
212
213
214 class Changes(Parameters):
215 def to_return(self):
216 result = {}
217 try:
218 for returnable in self.returnables:
219 result[returnable] = getattr(self, returnable)
220 result = self._filter_params(result)
221 except Exception:
222 raise
223 return result
224
225
226 class UsableChanges(Changes):
227 pass
228
229
230 class ReportableChanges(Changes):
231 pass
232
233
234 class Difference(object):
235 def __init__(self, want, have=None):
236 self.want = want
237 self.have = have
238
239 def compare(self, param):
240 try:
241 result = getattr(self, param)
242 return result
243 except AttributeError:
244 return self.__default(param)
245
246 def __default(self, param):
247 attr1 = getattr(self.want, param)
248 try:
249 attr2 = getattr(self.have, param)
250 if attr1 != attr2:
251 return attr1
252 except AttributeError:
253 return attr1
254
255 @property
256 def key_checksum(self):
257 if self.want.key_checksum is None:
258 return None
259 if self.want.key_checksum != self.have.checksum:
260 return self.want.key_checksum
261
262 @property
263 def key_source_path(self):
264 if self.want.key_source_path is None:
265 return None
266 if self.want.key_source_path == self.have.key_source_path:
267 if self.key_checksum:
268 return self.want.key_source_path
269 if self.want.key_source_path != self.have.key_source_path:
270 return self.want.key_source_path
271
272
273 class ModuleManager(object):
274 def __init__(self, *args, **kwargs):
275 self.module = kwargs.get('module', None)
276 self.client = F5RestClient(**self.module.params)
277 self.want = ModuleParameters(params=self.module.params)
278 self.have = ApiParameters()
279 self.changes = UsableChanges()
280
281 def _announce_deprecations(self, result):
282 warnings = result.pop('__warnings', [])
283 for warning in warnings:
284 self.client.module.deprecate(
285 msg=warning['msg'],
286 version=warning['version']
287 )
288
289 def _set_changed_options(self):
290 changed = {}
291 for key in Parameters.returnables:
292 if getattr(self.want, key) is not None:
293 changed[key] = getattr(self.want, key)
294 if changed:
295 self.changes = UsableChanges(params=changed)
296
297 def _update_changed_options(self):
298 diff = Difference(self.want, self.have)
299 updatables = Parameters.updatables
300 changed = dict()
301 for k in updatables:
302 change = diff.compare(k)
303 if change is None:
304 continue
305 else:
306 if isinstance(change, dict):
307 changed.update(change)
308 else:
309 changed[k] = change
310 if changed:
311 self.changes = UsableChanges(params=changed)
312 return True
313 return False
314
315 def exec_module(self):
316 start = datetime.now().isoformat()
317 version = tmos_version(self.client)
318 changed = False
319 result = dict()
320 state = self.want.state
321
322 if state == "present":
323 changed = self.present()
324 elif state == "absent":
325 changed = self.absent()
326
327 reportable = ReportableChanges(params=self.changes.to_return())
328 changes = reportable.to_return()
329 result.update(**changes)
330 result.update(dict(changed=changed))
331 self._announce_deprecations(result)
332 send_teem(start, self.client, self.module, version)
333 return result
334
335 def present(self):
336 if self.exists():
337 return self.update()
338 else:
339 return self.create()
340
341 def absent(self):
342 if self.exists():
343 return self.remove()
344 return False
345
346 def update(self):
347 self.have = self.read_current_from_device()
348 if not self.should_update():
349 return False
350 if self.module.check_mode:
351 return True
352 self.update_on_device()
353 self.remove_uploaded_file_from_device(self.want.key_filename)
354 return True
355
356 def should_update(self):
357 result = self._update_changed_options()
358 if result:
359 return True
360 return False
361
362 def create(self):
363 if self.want.content is None:
364 return False
365 self._set_changed_options()
366 if self.module.check_mode:
367 return True
368 self.create_on_device()
369 self.remove_uploaded_file_from_device(self.want.key_filename)
370 return True
371
372 def remove(self):
373 if self.module.check_mode:
374 return True
375 self.remove_from_device()
376 if self.exists():
377 raise F5ModuleError("Failed to delete the key")
378 return True
379
380 def remove_uploaded_file_from_device(self, name):
381 filepath = '/var/config/rest/downloads/{0}'.format(name)
382 params = {
383 "command": "run",
384 "utilCmdArgs": filepath
385 }
386 uri = "https://{0}:{1}/mgmt/tm/util/unix-rm".format(
387 self.client.provider['server'],
388 self.client.provider['server_port']
389 )
390 resp = self.client.api.post(uri, json=params)
391 try:
392 response = resp.json()
393 except ValueError as ex:
394 raise F5ModuleError(str(ex))
395 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
396 return True
397 raise F5ModuleError(resp.content)
398
399 def exists(self):
400 uri = "https://{0}:{1}/mgmt/tm/sys/file/ssl-key/{2}".format(
401 self.client.provider['server'],
402 self.client.provider['server_port'],
403 transform_name(self.want.partition, self.want.key_filename)
404 )
405 resp = self.client.api.get(uri)
406 try:
407 response = resp.json()
408 except ValueError as ex:
409 raise F5ModuleError(str(ex))
410
411 if resp.status == 404 or 'code' in response and response['code'] == 404:
412 return False
413 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
414 return True
415
416 errors = [401, 403, 409, 500, 501, 502, 503, 504]
417
418 if resp.status in errors or 'code' in response and response['code'] in errors:
419 if 'message' in response:
420 raise F5ModuleError(response['message'])
421 else:
422 raise F5ModuleError(resp.content)
423
424 def upload_file_to_device(self, content, name):
425 url = 'https://{0}:{1}/mgmt/shared/file-transfer/uploads'.format(
426 self.client.provider['server'],
427 self.client.provider['server_port']
428 )
429 try:
430 upload_file(self.client, url, content, name)
431 except F5ModuleError:
432 raise F5ModuleError(
433 "Failed to upload the file."
434 )
435
436 def update_on_device(self):
437 content = StringIO(self.want.content)
438 self.upload_file_to_device(content, self.want.key_filename)
439 params = self.changes.api_params()
440 uri = "https://{0}:{1}/mgmt/tm/sys/file/ssl-key/{2}".format(
441 self.client.provider['server'],
442 self.client.provider['server_port'],
443 transform_name(self.want.partition, self.want.key_filename)
444 )
445 resp = self.client.api.put(uri, json=params)
446 try:
447 response = resp.json()
448 except ValueError as ex:
449 raise F5ModuleError(str(ex))
450
451 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
452 return True
453
454 raise F5ModuleError(resp.content)
455
456 def create_on_device(self):
457 params = self.changes.api_params()
458 content = StringIO(self.want.content)
459 self.upload_file_to_device(content, self.want.key_filename)
460 params['name'] = self.want.key_filename
461 params['partition'] = self.want.partition
462 uri = "https://{0}:{1}/mgmt/tm/sys/file/ssl-key/".format(
463 self.client.provider['server'],
464 self.client.provider['server_port'],
465 )
466 resp = self.client.api.post(uri, json=params)
467 try:
468 response = resp.json()
469 except ValueError as ex:
470 raise F5ModuleError(str(ex))
471
472 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
473 return True
474
475 raise F5ModuleError(resp.content)
476
477 def read_current_from_device(self):
478 uri = "https://{0}:{1}/mgmt/tm/sys/file/ssl-key/{2}".format(
479 self.client.provider['server'],
480 self.client.provider['server_port'],
481 transform_name(self.want.partition, self.want.key_filename)
482 )
483 resp = self.client.api.get(uri)
484 try:
485 response = resp.json()
486 except ValueError as ex:
487 raise F5ModuleError(str(ex))
488
489 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
490 return ApiParameters(params=response)
491 raise F5ModuleError(resp.content)
492
493 def remove_from_device(self):
494 uri = "https://{0}:{1}/mgmt/tm/sys/file/ssl-key/{2}".format(
495 self.client.provider['server'],
496 self.client.provider['server_port'],
497 transform_name(self.want.partition, self.want.key_filename)
498 )
499 response = self.client.api.delete(uri)
500 if response.status == 200:
501 return True
502 raise F5ModuleError(response.content)
503
504
505 class ArgumentSpec(object):
506 def __init__(self):
507 self.supports_check_mode = True
508 argument_spec = dict(
509 name=dict(
510 required=True
511 ),
512 true_names=dict(
513 type='bool',
514 default='no'
515 ),
516 content=dict(
517 aliases=['key_content'],
518 no_log=True
519 ),
520 passphrase=dict(
521 no_log=True
522 ),
523 state=dict(
524 required=False,
525 default='present',
526 choices=['absent', 'present']
527 ),
528 partition=dict(
529 default='Common',
530 fallback=(env_fallback, ['F5_PARTITION'])
531 )
532 )
533 self.argument_spec = {}
534 self.argument_spec.update(f5_argument_spec)
535 self.argument_spec.update(argument_spec)
536
537
538 def main():
539 spec = ArgumentSpec()
540
541 module = AnsibleModule(
542 argument_spec=spec.argument_spec,
543 supports_check_mode=spec.supports_check_mode
544 )
545
546 try:
547 mm = ModuleManager(module=module)
548 results = mm.exec_module()
549 module.exit_json(**results)
550 except F5ModuleError as ex:
551 module.fail_json(msg=str(ex))
552
553
554 if __name__ == '__main__':
555 main()