Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2019, 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_csr
13 short_description: Create SSL CSR files on the BIG-IP
14 description:
15 - This module will create SSL CSR files on a BIG-IP. CSRs
16 require an associated SSL key to pre-exist on the BIG-IP.
17 version_added: "1.3.0"
18 options:
19 name:
20 description:
21 - The name of the CSR file.
22 type: str
23 required: True
24 common_name:
25 description:
26 - The certificate common name.
27 type: str
28 key_name:
29 description:
30 - The SSL key to be used to generate the CSR.
31 type: str
32 state:
33 description:
34 - When C(present), ensures the resource exists.
35 - When C(absent), ensures the resource does not exist.
36 type: str
37 choices:
38 - present
39 - absent
40 default: present
41 dest:
42 description:
43 - Destination on your local filesystem when you want to save the CSR file.
44 type: path
45 required: True
46 force:
47 description:
48 - If C(false), the file will only be transferred if the destination does not
49 exist.
50 type: bool
51 default: true
52 extends_documentation_fragment: f5networks.f5_modules.f5
53 author:
54 - Nitin Khanna (@nitinthewiz)
55 '''
56
57 EXAMPLES = r'''
58 - name: Create an SSL csr
59 bigip_ssl_csr:
60 name: csr-name
61 key_name: key-name
62 common_name: csr-name
63 dest: /tmp/csr-name
64 provider:
65 password: secret
66 server: lb.mydomain.com
67 user: admin
68 delegate_to: localhost
69 '''
70
71 RETURN = r'''
72 csr_name:
73 description: The name of the CSR file.
74 returned: created
75 type: str
76 sample: csr-name
77 common_name:
78 description: The common name of the CSR file.
79 returned: created
80 type: str
81 sample: csr-name
82 '''
83
84 import os
85 import traceback
86 from datetime import datetime
87
88 try:
89 from packaging.version import Version
90 except ImportError:
91 HAS_PACKAGING = False
92 Version = None
93 PACKAGING_IMPORT_ERROR = traceback.format_exc()
94 else:
95 HAS_PACKAGING = True
96 PACKAGING_IMPORT_ERROR = None
97
98 from ansible.module_utils.basic import (
99 AnsibleModule, missing_required_lib
100 )
101
102 from ..module_utils.bigip import F5RestClient
103 from ..module_utils.common import (
104 F5ModuleError, AnsibleF5Parameters, f5_argument_spec
105 )
106 from ..module_utils.icontrol import (
107 download_file, tmos_version
108 )
109 from ..module_utils.teem import send_teem
110
111
112 class Parameters(AnsibleF5Parameters):
113 api_map = {
114 'commonName': 'common_name',
115 'key': 'key_name'
116 }
117
118 api_attributes = [
119 'commonName',
120 'key'
121 ]
122
123 returnables = [
124 'csr_name',
125 'common_name'
126 ]
127
128 updatables = [
129
130 ]
131
132
133 class ApiParameters(Parameters):
134 pass
135
136
137 class ModuleParameters(Parameters):
138 pass
139
140
141 class Changes(Parameters):
142 def to_return(self):
143 result = {}
144 try:
145 for returnable in self.returnables:
146 result[returnable] = getattr(self, returnable)
147 result = self._filter_params(result)
148 except Exception:
149 pass
150 return result
151
152
153 class UsableChanges(Changes):
154 pass
155
156
157 class ReportableChanges(Changes):
158 pass
159
160
161 class Difference(object):
162 def __init__(self, want, have=None):
163 self.want = want
164 self.have = have
165
166 def compare(self, param):
167 try:
168 result = getattr(self, param)
169 return result
170 except AttributeError:
171 return self.__default(param)
172
173 def __default(self, param):
174 attr1 = getattr(self.want, param)
175 try:
176 attr2 = getattr(self.have, param)
177 if attr1 != attr2:
178 return attr1
179 except AttributeError:
180 return attr1
181
182
183 class ModuleManager(object):
184 def __init__(self, *args, **kwargs):
185 self.module = kwargs.get('module', None)
186 self.client = F5RestClient(**self.module.params)
187 self.want = ModuleParameters(params=self.module.params)
188 self.have = ApiParameters()
189 self.changes = UsableChanges()
190 self.remote_dir = '/var/config/rest/bulk'
191
192 def _set_changed_options(self):
193 changed = {}
194 for key in Parameters.returnables:
195 if getattr(self.want, key) is not None:
196 changed[key] = getattr(self.want, key)
197 if changed:
198 self.changes = UsableChanges(params=changed)
199
200 def _announce_deprecations(self, result):
201 warnings = result.pop('__warnings', [])
202 for warning in warnings:
203 self.client.module.deprecate(
204 msg=warning['msg'],
205 version=warning['version']
206 )
207
208 def exec_module(self):
209 start = datetime.now().isoformat()
210 version = tmos_version(self.client)
211 if self.version_is_less_than_14(version):
212 raise F5ModuleError(
213 "This module requires TMOS version 14.x and above."
214 )
215
216 changed = False
217 result = dict()
218 state = self.want.state
219
220 if state == "present":
221 changed = self.present()
222 elif state == "absent":
223 changed = self.absent()
224
225 reportable = ReportableChanges(params=self.changes.to_return())
226 changes = reportable.to_return()
227 result.update(**changes)
228 result.update(dict(changed=changed))
229 self._announce_deprecations(result)
230 send_teem(start, self.client, self.module, version)
231 return result
232
233 def version_is_less_than_14(self, version):
234 if Version(version) < Version('14.0.0'):
235 return True
236 else:
237 return False
238
239 def present(self):
240 if os.path.exists(self.want.dest) and not self.want.force:
241 raise F5ModuleError(
242 "The specified 'dest' file already exists."
243 )
244 if not os.path.exists(os.path.dirname(self.want.dest)):
245 raise F5ModuleError(
246 "The directory of your 'dest' file does not exist."
247 )
248 if self.exists():
249 return False
250 else:
251 return self.execute()
252
253 def absent(self):
254 if self.exists():
255 return self.remove()
256 return False
257
258 def remove(self):
259 if self.module.check_mode:
260 return True
261 self.remove_from_device()
262 if self.exists():
263 raise F5ModuleError("Failed to delete the resource.")
264 return True
265
266 def execute(self):
267 response = self.create()
268 if not response:
269 raise F5ModuleError(
270 "Failed to create csr on device."
271 )
272
273 result = self._move_csr_to_download()
274 if not result:
275 raise F5ModuleError(
276 "Failed to move the csr file to a downloadable location"
277 )
278
279 self._download_file()
280 if not os.path.exists(self.want.dest):
281 raise F5ModuleError(
282 "Failed to save the csr file to local disk"
283 )
284
285 self._delete_csr()
286 result = self.file_exists()
287 if result:
288 raise F5ModuleError(
289 "Failed to remove the remote csr file"
290 )
291 return True
292
293 def create(self):
294 self._set_changed_options()
295 if self.module.check_mode:
296 return True
297 self.create_on_device()
298 return True
299
300 def exists(self):
301 uri = "https://{0}:{1}/mgmt/tm/sys/crypto/csr/{2}".format(
302 self.client.provider['server'],
303 self.client.provider['server_port'],
304 self.want.name
305 )
306 resp = self.client.api.get(uri)
307 try:
308 response = resp.json()
309 except ValueError as ex:
310 raise F5ModuleError(str(ex))
311
312 if resp.status == 404 or 'code' in response and response['code'] == 404:
313 return False
314 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
315 return True
316
317 errors = [401, 403, 409, 500, 501, 502, 503, 504]
318
319 if resp.status in errors or 'code' in response and response['code'] in errors:
320 if 'message' in response:
321 raise F5ModuleError(response['message'])
322 else:
323 raise F5ModuleError(resp.content)
324
325 def create_on_device(self):
326 params = self.changes.api_params()
327 params['name'] = self.want.name
328 params['partition'] = self.want.partition
329 params['key'] = self.want.key_name
330 uri = "https://{0}:{1}/mgmt/tm/sys/crypto/csr/".format(
331 self.client.provider['server'],
332 self.client.provider['server_port'],
333 )
334 resp = self.client.api.post(uri, json=params)
335 try:
336 response = resp.json()
337 except ValueError as ex:
338 raise F5ModuleError(str(ex))
339
340 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
341 return True
342 raise F5ModuleError(resp.content)
343
344 def remove_from_device(self):
345 uri = "https://{0}:{1}/mgmt/tm/sys/crypto/csr/{2}".format(
346 self.client.provider['server'],
347 self.client.provider['server_port'],
348 self.want.name
349 )
350 response = self.client.api.delete(uri)
351
352 if response.status in [200, 201]:
353 return True
354 raise F5ModuleError(response.content)
355
356 def file_exists(self):
357 tpath_name = '{0}/{1}'.format(self.remote_dir, self.want.name)
358 params = dict(
359 command='run',
360 utilCmdArgs=tpath_name
361 )
362 uri = "https://{0}:{1}/mgmt/tm/util/unix-ls".format(
363 self.client.provider['server'],
364 self.client.provider['server_port'],
365 )
366 resp = self.client.api.post(uri, json=params)
367 try:
368 response = resp.json()
369 except ValueError:
370 return False
371 if resp.status == 404 or 'code' in response and response['code'] == 404:
372 return False
373
374 try:
375 if "No such file or directory" in response['commandResult']:
376 return False
377 if self.want.name in response['commandResult']:
378 return True
379 except KeyError:
380 return False
381
382 def _download_file(self):
383 uri = "https://{0}:{1}/mgmt/shared/file-transfer/bulk/{2}".format(
384 self.client.provider['server'],
385 self.client.provider['server_port'],
386 self.want.name
387 )
388 download_file(self.client, uri, self.want.dest)
389 if os.path.exists(self.want.dest):
390 return True
391 return False
392
393 def _delete_csr(self):
394 tpath_name = '{0}/{1}'.format(self.remote_dir, self.want.name)
395 params = dict(
396 command='run',
397 utilCmdArgs=tpath_name
398 )
399 uri = "https://{0}:{1}/mgmt/tm/util/unix-rm".format(
400 self.client.provider['server'],
401 self.client.provider['server_port'],
402 )
403 resp = self.client.api.post(uri, json=params)
404 try:
405 response = resp.json()
406 except ValueError:
407 return False
408 if resp.status == 404 or 'code' in response and response['code'] == 404:
409 return False
410
411 def _move_csr_to_download(self):
412 uri = "https://{0}:{1}/mgmt/tm/util/unix-mv/".format(
413 self.client.provider['server'],
414 self.client.provider['server_port']
415 )
416 args = dict(
417 command='run',
418 utilCmdArgs='/config/ssl/ssl.csr/{0} {1}/{0}'.format(self.want.name, self.remote_dir)
419 )
420 self.client.api.post(uri, json=args)
421 return True
422
423
424 class ArgumentSpec(object):
425 def __init__(self):
426 self.supports_check_mode = True
427 argument_spec = dict(
428 name=dict(
429 required=True
430 ),
431 common_name=dict(),
432 key_name=dict(),
433 state=dict(
434 default='present',
435 choices=['present', 'absent']
436 ),
437 dest=dict(
438 type='path',
439 required=True
440 ),
441 force=dict(
442 default=True,
443 type='bool'
444 )
445 )
446 self.argument_spec = {}
447 self.argument_spec.update(f5_argument_spec)
448 self.argument_spec.update(argument_spec)
449
450 self.required_if = [
451 ['state', 'present', ['common_name', 'key_name']]
452 ]
453
454
455 def main():
456 spec = ArgumentSpec()
457
458 module = AnsibleModule(
459 argument_spec=spec.argument_spec,
460 supports_check_mode=spec.supports_check_mode,
461 )
462
463 if not HAS_PACKAGING:
464 module.fail_json(
465 msg=missing_required_lib('packaging'),
466 exception=PACKAGING_IMPORT_ERROR
467 )
468
469 try:
470 mm = ModuleManager(module=module)
471 results = mm.exec_module()
472 module.exit_json(**results)
473 except F5ModuleError as ex:
474 module.fail_json(msg=str(ex))
475
476
477 if __name__ == '__main__':
478 main()